feat: add ability of user to manage old tokens

This commit is contained in:
Andre Henriques 2024-04-13 16:59:08 +01:00
parent f8bc8ad85a
commit 4862e9a79e
6 changed files with 421 additions and 197 deletions

View File

@ -106,7 +106,6 @@ func fileProcessor(
func processZipFile(c *Context, model *BaseModel) { func processZipFile(c *Context, model *BaseModel) {
var err error var err error
failed := func(msg string) { failed := func(msg string) {
@ -202,7 +201,6 @@ func processZipFile(c *Context, model *BaseModel) {
file_chans[channel_to_send] <- file file_chans[channel_to_send] <- file
if first_round { if first_round {
channel_to_send += 1 channel_to_send += 1
if c.Handle.Config.NumberOfWorkers == channel_to_send { if c.Handle.Config.NumberOfWorkers == channel_to_send {
@ -342,7 +340,6 @@ func processZipFileExpand(c *Context, model *BaseModel) {
file_chans[channel_to_send] <- file file_chans[channel_to_send] <- file
if first_round { if first_round {
channel_to_send += 1 channel_to_send += 1
if c.Handle.Config.NumberOfWorkers == channel_to_send { if c.Handle.Config.NumberOfWorkers == channel_to_send {
@ -376,7 +373,6 @@ func processZipFileExpand(c *Context, model *BaseModel) {
ModelUpdateStatus(c, model.Id, READY) ModelUpdateStatus(c, model.Id, READY)
} }
func handleRemoveDataPoint(c *Context) *Error { func handleRemoveDataPoint(c *Context) *Error {
var dat JustId var dat JustId
if err := c.ToJSON(&dat); err != nil { if err := c.ToJSON(&dat); err != nil {
@ -530,7 +526,7 @@ func handleDataUpload(handle *Handle) {
return c.SendJSON(model.Id) return c.SendJSON(model.Id)
}) })
handle.Delete("/models/data/point", handleRemoveDataPoint) handle.DeleteAuth("/models/data/point", 1, handleRemoveDataPoint)
handle.Delete("/models/data/delete-zip-file", func(c *Context) *Error { handle.Delete("/models/data/delete-zip-file", func(c *Context) *Error {
if !c.CheckAuthLevel(1) { if !c.CheckAuthLevel(1) {

View File

@ -91,6 +91,24 @@ func (x *Handle) PostAuth(path string, authLevel int, fn func(c *Context) *Error
x.posts = append(x.posts, HandleFunc{path, inner_fn}) x.posts = append(x.posts, HandleFunc{path, inner_fn})
} }
func PostAuthJson[T interface{}](x *Handle, path string, authLevel int, fn func(c *Context, obj *T) *Error) {
inner_fn := func(c *Context) *Error {
if !c.CheckAuthLevel(authLevel) {
return nil
}
obj := new(T)
if err := c.ToJSON(obj); err != nil {
return err
}
return fn(c, obj)
}
x.posts = append(x.posts, HandleFunc{path, inner_fn})
}
func (x *Handle) Delete(path string, fn func(c *Context) *Error) { func (x *Handle) Delete(path string, fn func(c *Context) *Error) {
x.deletes = append(x.deletes, HandleFunc{path, fn}) x.deletes = append(x.deletes, HandleFunc{path, fn})
} }
@ -105,6 +123,24 @@ func (x *Handle) DeleteAuth(path string, authLevel int, fn func(c *Context) *Err
x.posts = append(x.posts, HandleFunc{path, inner_fn}) x.posts = append(x.posts, HandleFunc{path, inner_fn})
} }
func DeleteAuthJson[T interface{}](x *Handle, path string, authLevel int, fn func(c *Context, obj *T) *Error) {
inner_fn := func(c *Context) *Error {
if !c.CheckAuthLevel(authLevel) {
return nil
}
obj := new(T)
if err := c.ToJSON(obj); err != nil {
return err
}
return fn(c, obj)
}
x.deletes = append(x.deletes, HandleFunc{path, inner_fn})
}
func (x *Handle) handleGets(context *Context) { func (x *Handle) handleGets(context *Context) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
@ -185,12 +221,11 @@ type Context struct {
Handle *Handle Handle *Handle
} }
func (c Context) GetDb() *sql.DB {
func (c Context) GetDb() (*sql.DB) {
return c.Db return c.Db
} }
func (c Context) GetLogger() (*log.Logger) { func (c Context) GetLogger() *log.Logger {
return c.Logger return c.Logger
} }
@ -198,7 +233,6 @@ func (c Context) Query(query string, args ...any) (*sql.Rows, error) {
return c.Db.Query(query, args...) return c.Db.Query(query, args...)
} }
func (c Context) Prepare(str string) (*sql.Stmt, error) { func (c Context) Prepare(str string) (*sql.Stmt, error) {
if c.Tx == nil { if c.Tx == nil {
return c.Db.Prepare(str) return c.Db.Prepare(str)
@ -262,13 +296,13 @@ func (c Context) decodeAndValidade(decoder *json.Decoder, dat any) *Error {
err := decoder.Decode(dat) err := decoder.Decode(dat)
if err != nil { if err != nil {
c.Logger.Error("Failed to decode json", "dat", dat, "err", err) c.Logger.Error("Failed to decode json", "dat", dat, "err", err)
return c.JsonBadRequest("Bad Request! Invalid json passed!"); return c.JsonBadRequest("Bad Request! Invalid json passed!")
} }
err = c.Handle.validate.Struct(dat) err = c.Handle.validate.Struct(dat)
if err != nil { if err != nil {
c.Logger.Error("Failed invalid json passed", "dat", dat, "err", err) c.Logger.Error("Failed invalid json passed", "dat", dat, "err", err)
return c.JsonBadRequest("Bad Request! Invalid json passed!"); return c.JsonBadRequest("Bad Request! Invalid json passed!")
} }
return nil return nil

View File

@ -22,6 +22,6 @@ create table if not exists tokens (
token varchar (120) primary key, token varchar (120) primary key,
user_id uuid references users (id) on delete cascade, user_id uuid references users (id) on delete cascade,
time_to_live integer default 86400, time_to_live integer default 86400,
name text default '',
emit_day timestamp default current_timestamp emit_day timestamp default current_timestamp
); );

View File

@ -6,6 +6,7 @@ import (
"encoding/hex" "encoding/hex"
"io" "io"
"net/http" "net/http"
"time"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@ -41,7 +42,12 @@ func genToken() string {
return hex.EncodeToString(token) return hex.EncodeToString(token)
} }
func generateToken(db *sql.DB, email string, password string) (string, bool) { func deleteToken(db *sql.DB, userId string, time time.Time) (err error) {
_, err = db.Exec("delete from tokens where emit_day=$1 and user_id=$2", time, userId)
return
}
func generateToken(db *sql.DB, email string, password string, name string) (string, bool) {
row, err := db.Query("select id, salt, password from users where email = $1;", email) row, err := db.Query("select id, salt, password from users where email = $1;", email)
if err != nil || !row.Next() { if err != nil || !row.Next() {
return "", false return "", false
@ -66,7 +72,7 @@ func generateToken(db *sql.DB, email string, password string) (string, bool) {
token := genToken() token := genToken()
_, err = db.Exec("insert into tokens (user_id, token) values ($1, $2);", db_id, token) _, err = db.Exec("insert into tokens (user_id, token, name) values ($1, $2, $3);", db_id, token, name)
if err != nil { if err != nil {
return "", false return "", false
} }
@ -88,7 +94,7 @@ func usersEndpints(db *sql.DB, handle *Handle) {
} }
// TODO Give this to the generateToken function // TODO Give this to the generateToken function
token, login := generateToken(db, dat.Email, dat.Password) token, login := generateToken(db, dat.Email, dat.Password, "Logged in user")
if !login { if !login {
return c.SendJSONStatus(http.StatusUnauthorized, "Email or password are incorrect") return c.SendJSONStatus(http.StatusUnauthorized, "Email or password are incorrect")
} }
@ -172,7 +178,7 @@ func usersEndpints(db *sql.DB, handle *Handle) {
} }
// TODO Give this to the generateToken function // TODO Give this to the generateToken function
token, login := generateToken(db, dat.Email, dat.Password) token, login := generateToken(db, dat.Email, dat.Password, "User Login")
if !login { if !login {
return c.SendJSONStatus(500, "Could not login after creatting account please try again later") return c.SendJSONStatus(500, "Could not login after creatting account please try again later")
} }
@ -330,9 +336,8 @@ func usersEndpints(db *sql.DB, handle *Handle) {
return c.JsonBadRequest("New passwords did not match") return c.JsonBadRequest("New passwords did not match")
} }
c.Logger.Warn("test", "dat", dat) // TODO remote token
_, login := generateToken(db, c.User.Email, dat.Old_Password, "Update password Token")
_, login := generateToken(db, c.User.Email, dat.Old_Password)
if !login { if !login {
return c.JsonBadRequest("Password is incorrect") return c.JsonBadRequest("Password is incorrect")
} }
@ -351,5 +356,55 @@ func usersEndpints(db *sql.DB, handle *Handle) {
return c.SendJSON(c.User.Id) return c.SendJSON(c.User.Id)
}) })
type TokenList struct {
Id string `json:"id"`
Page int `json:"page"`
}
PostAuthJson[TokenList](handle, "/user/token/list", 1, func(c *Context, obj *TokenList) *Error {
if obj.Id == "" {
obj.Id = c.User.Id
}
if obj.Id != c.User.Id && c.User.UserType < int(dbtypes.User_Admin) {
return c.JsonBadRequest("Could not find user tokens")
}
type Token struct {
CreationDate time.Time `json:"create_date" db:"emit_day"`
TimeToLive int `json:"time_to_live" db:"time_to_live"`
Name string `json:"name"`
}
tokens, err := GetDbMultitple[Token](c, "tokens where user_id=$1 order by emit_day desc limit 11 offset $2;", obj.Id, 10*obj.Page)
if err != nil {
return c.E500M("Failed get tokens", err)
}
max_len := min(11, len(tokens))
c.ShowMessage = false
return c.SendJSON(struct {
TokenList []*Token `json:"token_list"`
ShowNext bool `json:"show_next"`
}{
tokens[0:max_len],
len(tokens) > 10,
})
})
type TokenDelete struct {
Time time.Time `json:"time" validate:"required"`
}
DeleteAuthJson(handle, "/user/token", 1, func(c *Context, obj *TokenDelete) *Error {
// TODO allow admin user to delete to other persons token
err := deleteToken(c.Db, c.User.Id, obj.Time)
if err != nil {
return c.E500M("Could not delete token", err)
}
return c.SendJSON("Ok")
})
// TODO create function to remove token // TODO create function to remove token
} }

View File

@ -6,6 +6,7 @@
import 'src/styles/forms.css'; import 'src/styles/forms.css';
import { post } from 'src/lib/requests.svelte'; import { post } from 'src/lib/requests.svelte';
import MessageSimple, { type DisplayFn } from 'src/lib/MessageSimple.svelte'; import MessageSimple, { type DisplayFn } from 'src/lib/MessageSimple.svelte';
import TokenTable from './TokenTable.svelte';
onMount(() => { onMount(() => {
if (!userStore.isLogin()) { if (!userStore.isLogin()) {
@ -110,6 +111,7 @@
</div> </div>
</form> </form>
<!-- TODO Delete --> <!-- TODO Delete -->
<TokenTable />
</div> </div>
</div> </div>

View File

@ -0,0 +1,137 @@
<script lang="ts" context="module">
export type Token = {
create_date: string;
time_to_live: number;
name: string;
};
</script>
<script lang="ts">
import { post, rdelete } from 'src/lib/requests.svelte';
import { userStore } from 'src/routes/UserStore.svelte';
let page = $state(0);
let showNext = $state(false);
let token_list: Token[] = $state([]);
export async function getList() {
if (!userStore.user) {
return;
}
try {
const res = await post('user/token/list', {
id: userStore.user.id,
page: page
});
token_list = res.token_list;
showNext = res.show_next;
} catch (e) {
console.error('TODO notify user', e);
}
}
async function removeToken(token: Token) {
try {
rdelete('user/token', { time: token.create_date });
getList();
} catch (e) {
console.error('Notify the user', e);
}
}
$effect(() => {
if (userStore.user) {
getList();
}
});
</script>
<div>
<h2>Tokens</h2>
<table>
<thead>
<tr>
<th> Name </th>
<th> Created </th>
<th>
<!-- Delete -->
</th>
</tr>
</thead>
<tbody>
{#each token_list as token}
<tr>
<td>
{token.name}
</td>
<td>
{new Date(token.create_date).toLocaleString()}
</td>
<td>
<button class="danger" on:click={() => removeToken(token)}>
<span class="bi bi-trash"></span>
</button>
</td>
</tr>
{/each}
</tbody>
</table>
<div class="flex justify-center align-center">
<div class="grow-1 flex justify-end align-center">
{#if page > 0}
<button on:click={() => (page -= 1)}> Prev </button>
{/if}
</div>
<div style="padding: 10px;">
{page}
</div>
<div class="grow-1 flex justify-start align-center">
{#if showNext}
<button on:click={() => (page += 1)}> Next </button>
{/if}
</div>
</div>
</div>
<style lang="scss">
.buttons {
width: 100%;
display: flex;
justify-content: space-between;
& > button {
margin: 3px 5px;
}
}
table {
width: 100%;
box-shadow: 0 2px 8px 1px #66666622;
border-radius: 10px;
border-collapse: collapse;
overflow: hidden;
}
table thead {
background: #60606022;
}
table tr td,
table tr th {
border-left: 1px solid #22222244;
padding: 15px;
}
table tr td:first-child,
table tr th:first-child {
border-left: none;
}
table tr td button,
table tr td .button {
padding: 5px 10px;
box-shadow: 0 2px 5px 1px #66666655;
}
</style>