-
Notifications
You must be signed in to change notification settings - Fork 41
/
token.go
92 lines (86 loc) · 2.1 KB
/
token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package api
import (
"database/sql"
"github.com/gin-gonic/gin"
"github.com/joschahenningsen/TUM-Live/dao"
"github.com/joschahenningsen/TUM-Live/model"
"github.com/joschahenningsen/TUM-Live/tools"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"net/http"
"time"
)
func configTokenRouter(r *gin.Engine, daoWrapper dao.DaoWrapper) {
routes := tokenRoutes{daoWrapper}
g := r.Group("/api/token")
g.Use(tools.Admin)
g.POST("/create", routes.createToken)
g.DELETE("/:id", routes.deleteToken)
}
type tokenRoutes struct {
dao.DaoWrapper
}
func (r tokenRoutes) deleteToken(c *gin.Context) {
id := c.Param("id")
err := r.TokenDao.DeleteToken(id)
if err != nil {
log.WithError(err).Error("can not delete token")
_ = c.Error(tools.RequestError{
Status: http.StatusInternalServerError,
CustomMessage: "can not delete token",
Err: err,
})
return
}
}
func (r tokenRoutes) createToken(c *gin.Context) {
foundContext, exists := c.Get("TUMLiveContext")
if !exists {
return
}
tumLiveContext := foundContext.(tools.TUMLiveContext)
var req struct {
Expires *time.Time `json:"expires"`
Scope string `json:"scope"`
}
err := c.BindJSON(&req)
if err != nil {
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "can not bind body",
Err: err,
})
return
}
if req.Scope != model.TokenScopeAdmin {
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "not an admin",
})
return
}
tokenStr := uuid.NewV4().String()
expires := sql.NullTime{Valid: req.Expires != nil}
if req.Expires != nil {
expires.Time = *req.Expires
}
token := model.Token{
UserID: tumLiveContext.User.ID,
Token: tokenStr,
Expires: expires,
Scope: req.Scope,
}
err = r.TokenDao.AddToken(token)
if err != nil {
log.WithError(err).Error("can not create token")
_ = c.Error(tools.RequestError{
Status: http.StatusInternalServerError,
CustomMessage: "can not create token",
Err: err,
})
return
}
c.JSON(http.StatusOK, gin.H{
"token": tokenStr,
})
}