forked from semaphoreui/semaphore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
68 lines (54 loc) · 1.49 KB
/
user.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
package api
import (
"crypto/rand"
"encoding/base64"
"github.com/ansible-semaphore/semaphore/api/helpers"
"github.com/ansible-semaphore/semaphore/db"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"io"
"net/http"
"strings"
)
func getUser(w http.ResponseWriter, r *http.Request) {
if u, exists := context.GetOk(r, "_user"); exists {
helpers.WriteJSON(w, http.StatusOK, u)
return
}
helpers.WriteJSON(w, http.StatusOK, context.Get(r, "user"))
}
func getAPITokens(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*db.User)
tokens, err := helpers.Store(r).GetAPITokens(user.ID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
helpers.WriteJSON(w, http.StatusOK, tokens)
}
func createAPIToken(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*db.User)
tokenID := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, tokenID); err != nil {
panic(err)
}
token, err := helpers.Store(r).CreateAPIToken(db.APIToken{
ID: strings.ToLower(base64.URLEncoding.EncodeToString(tokenID)),
UserID: user.ID,
Expired: false,
})
if err != nil {
panic(err)
}
helpers.WriteJSON(w, http.StatusCreated, token)
}
func expireAPIToken(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*db.User)
tokenID := mux.Vars(r)["token_id"]
err := helpers.Store(r).ExpireAPIToken(user.ID, tokenID)
if err != nil {
helpers.WriteError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}