-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
73 lines (61 loc) · 2.37 KB
/
auth.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
package handlers
import (
"encoding/base64"
"encoding/json"
"strings"
scrypt "github.com/elithrar/simple-scrypt"
"github.com/mikeStr8s/simple_weapons_api/util"
"github.com/valyala/fasthttp"
)
// Register is the registration handler to create an account
// to allow the user to traverse the API through the auth middleware
func Register(ctx *fasthttp.RequestCtx) {
// If there is unique username, create the new user and return the login token
// Else return 409 because account with username already exists
if userData, exists := userExists(ctx.PostBody()); !exists {
newUser := createUser(userData)
util.SetResponse(ctx)
if err := json.NewEncoder(ctx).Encode(newUser); err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
} else {
ctx.Response.SetStatusCode(409)
}
}
// Login allows returning users to get their auth token
// to login to the applications REST functions
func Login(ctx *fasthttp.RequestCtx) {
if _, exists := userExists(ctx.PostBody()); exists {
var postData map[string]string
json.Unmarshal(ctx.PostBody(), &postData)
token := base64.StdEncoding.EncodeToString([]byte(strings.Join([]string{postData["username"], postData["password"]}, ":")))
util.SetResponse(ctx)
if err := json.NewEncoder(ctx).Encode(map[string]string{"token": string(token)}); err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
} else {
ctx.Response.SetStatusCode(401)
}
}
func userExists(byteData []byte) (postBody map[string]string, exists bool) {
var postData map[string]string
json.Unmarshal(byteData, &postData)
userByteData := util.ReadJSONFile("user")
var userData map[string]string
json.Unmarshal(userByteData, &userData)
if val, ok := userData[postData["username"]]; ok {
return map[string]string{"token": val}, true
}
return postData, false
}
func createUser(postData map[string]string) map[string]string {
authHash, _ := scrypt.GenerateFromPassword([]byte(postData["password"]), scrypt.DefaultParams)
userByteData := util.ReadJSONFile("user")
var userData map[string]string
json.Unmarshal(userByteData, &userData)
userData[postData["username"]] = string(authHash)
userJSON, _ := json.Marshal(userData)
WriteJSONData("user", userJSON)
token := base64.StdEncoding.EncodeToString([]byte(strings.Join([]string{postData["username"], postData["password"]}, ":")))
return map[string]string{"token": string(token)}
}