0 package gmi
1
2 import (
3 "log"
4 "strconv"
5
6 "gemigit/db"
7
8 "github.com/pitr/gig"
9 )
10
11 func CreateToken(c gig.Context) error {
12
13 user, exist := db.GetUser(c.CertHash())
14 if !exist {
15 return c.NoContent(gig.StatusBadRequest, "Invalid username")
16 }
17
18 token, err := user.CreateToken()
19 if err != nil {
20 log.Println(err)
21 return c.NoContent(gig.StatusBadRequest, "Unexpected error")
22 }
23 data := struct {
24 Token string
25 }{
26 Token: token,
27 }
28 return execT(c, "token_new.gmi", data)
29 }
30
31 func ListTokens(c gig.Context) error {
32
33 user, exist := db.GetUser(c.CertHash())
34 if !exist {
35 return c.NoContent(gig.StatusBadRequest, "Invalid username")
36 }
37
38 tokens, err := user.GetTokens()
39 if err != nil {
40 log.Println(err)
41 return c.NoContent(gig.StatusBadRequest, "Unexpected error")
42 }
43
44 data := struct {
45 Tokens []db.Token
46 Secure bool
47 }{
48 Tokens: tokens,
49 Secure: user.SecureGit,
50 }
51 return execT(c, "token.gmi", data)
52 }
53
54 func ToggleTokenAuth(c gig.Context) error {
55
56 user, exist := db.GetUser(c.CertHash())
57 if !exist {
58 return c.NoContent(gig.StatusBadRequest, "Invalid username")
59 }
60
61 err := user.ToggleSecure()
62 if err != nil {
63 log.Println(err)
64 return c.NoContent(gig.StatusBadRequest, "Unexpected error")
65 }
66
67 return c.NoContent(gig.StatusRedirectTemporary, "/account/token")
68 }
69
70 func RenewToken(c gig.Context) error {
71
72 user, exist := db.GetUser(c.CertHash())
73 if !exist {
74 return c.NoContent(gig.StatusBadRequest, "Invalid username")
75 }
76
77 id, err := strconv.Atoi(c.Param("token"))
78 if err != nil || user.RenewToken(id) != nil {
79 return c.NoContent(gig.StatusBadRequest, "Invalid token")
80 }
81
82 return c.NoContent(gig.StatusRedirectTemporary, "/account/token")
83 }
84
85 func DeleteToken(c gig.Context) error {
86
87 user, exist := db.GetUser(c.CertHash())
88 if !exist {
89 return c.NoContent(gig.StatusBadRequest, "Invalid username")
90 }
91
92 id, err := strconv.Atoi(c.Param("token"))
93 if err != nil || user.DeleteToken(id) != nil {
94 return c.NoContent(gig.StatusBadRequest, "Invalid token")
95 }
96
97 return c.NoContent(gig.StatusRedirectTemporary, "/account/token")
98 }
99