-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
105 lines (97 loc) · 2.61 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package bellbox
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
"net/http"
)
func HandleNewUser(c *gin.Context) {
user := User{}
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "malformed json"})
return
}
if user.User == "" || user.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing required user or password"})
return
}
// get a database, try add this person to it
if UserExists(user.User) {
c.JSON(http.StatusConflict, gin.H{"error": "already exists"})
return
}
var db = GetConfig().Db.GetDb()
db.Create(&user)
token := NewToken(user.User)
ReplyToken(token, c)
}
func UserExists(user string) bool {
fmt.Printf("Checking if user %s exists\n", user)
var db = GetConfig().Db.GetDb()
username := User{}
db.Where("\"user\" = ?", user).Find(&username)
if username.Password != "" {
return true
}
return false
}
func NewToken(user string) string {
token := GenToken()
db.Create(&UserToken{User:user, Token:token, Timestamp: time.Now()})
return token
}
func ReplyToken(token string, c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"token": token})
}
type GinHandler func(*gin.Context)
func HandleUserAuth(handler GinHandler) func(*gin.Context) {
// Check if the user is permitted to continue
return func(c *gin.Context) {
a := c.Request.Header.Get("Authorization")
if a == "" {
c.JSON(http.StatusForbidden, gin.H{"error": "auth header not present"})
return
}
fmt.Println(a)
db := GetConfig().Db.GetDb()
token := UserToken{}
db.Where("token = ?", a).Find(&token)
if token.User == "" {
c.JSON(http.StatusForbidden, gin.H{"error": "auth rejected"})
return
}
fmt.Printf("Found user: %+v\n", token)
c.Request.Header.Set("UserId", token.User)
handler(c)
}
}
func HandleExistingUser(c *gin.Context) {
user := User{}
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "malformed json"})
return
}
if user.User == "" || user.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing fields"})
return
}
if !UserExists(user.User) {
c.JSON(http.StatusForbidden, gin.H{"error": "not exist or not match"})
return
}
// get a database, try add this person to it
var db = GetConfig().Db.GetDb()
uexist := User{}
db.Where("\"user\" = ?", user.User).Find(&uexist)
if uexist.Password == "" {
c.JSON(http.StatusForbidden, gin.H{"error": "not exist or not match"})
return
}
if user.Password != uexist.Password {
c.JSON(http.StatusForbidden, gin.H{"error": "not exist or not match"})
return
}
// OK, make token
token := NewToken(user.User)
ReplyToken(token, c)
}