-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
152 lines (129 loc) · 4.51 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
import (
"errors"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"net/http"
"strings"
)
// getUUID returns a randomly generated UUID
func getUUID() string {
return uuid.New().String()
}
// initCookies use gin-contrib/sessions{/cookie} to initalize a cookie store.
func initCookies(r *gin.Engine) {
//r.Use(sessions.Sessions("cybernet", cookie.NewStore([]byte(getUUID()))))
r.Use(sessions.Sessions("cybernet", cookie.NewStore([]byte("abcd"))))
}
// login is a handler that parses a form and checks for specific data
func login(c *gin.Context) {
session := sessions.Default(c)
username := c.PostForm("username")
password := c.PostForm("password")
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.HTML(http.StatusBadRequest, "login.html", pageData(c, "login", gin.H{"error": "Username or password can't be empty."}))
return
}
var user = &User{}
db.First(user, "username = ?", username)
if !user.IsValid() {
c.HTML(http.StatusBadRequest, "login.html", pageData(c, "login", gin.H{"error": errors.New("Invalid username or password.")}))
return
}
err := bcrypt.CompareHashAndPassword([]byte(user.HashedPw), []byte(password))
if err != nil {
c.HTML(http.StatusBadRequest, "login.html", pageData(c, "login", gin.H{"error": errors.New("Invalid username or password.")}))
return
}
session.Set("user", username)
if err := session.Save(); err != nil {
c.HTML(http.StatusBadRequest, "login.html", pageData(c, "login", gin.H{"error": "Failed to save session."}))
return
}
c.Redirect(http.StatusSeeOther, "/")
}
func register(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
secret := c.PostForm("secret")
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "Regster", gin.H{"error": "Username or password can't be empty.", "username": username, "secret": secret}))
return
}
var testUser = &User{}
db.First(testUser, "username = ?", username)
if testUser.IsValid() {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "login", gin.H{"error": errors.New("That username is taken."), "username": username, "secret": secret}))
return
}
var foundSecret = &Secret{}
db.Order("time desc").First(foundSecret)
if foundSecret.Secret != secret || foundSecret.Time.IsZero() {
db.Find(foundSecret, "secret = ?", secret)
if foundSecret.Time.IsZero() {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "Register", gin.H{"error": errors.New("Invalid secret!"), "username": username, "secret": secret}))
} else {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "Register", gin.H{"error": errors.New("Sorry, that secret is expired!"), "username": username, "secret": secret}))
}
return
}
givenPw, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "Register", gin.H{"error": err, "username": username, "secret": secret}))
return
}
user := User{
Username: username,
HashedPw: string(givenPw),
}
result := db.Create(&user)
if result.Error != nil {
c.HTML(http.StatusBadRequest, "register.html", pageData(c, "Register", gin.H{"error": err, "username": username, "secret": secret}))
}
c.HTML(http.StatusOK, "login.html", pageData(c, "Login", gin.H{"message": "Registration successfull! Please log in."}))
}
func getUser(c *gin.Context) *User {
session := sessions.Default(c)
username := session.Get("user")
var user = &User{}
db.Limit(1).Find(user, "username = ?", username)
return user
}
func logout(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
session.Delete("user")
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.Redirect(http.StatusSeeOther, "/")
}
// authRequired provides authentication middleware for ensuring that a user is logged in.
func authRequired(c *gin.Context) {
user := getUser(c)
if !user.IsValid() {
c.Redirect(http.StatusSeeOther, "/login")
c.Abort()
}
c.Next()
}
func adminRequired(c *gin.Context) {
user := getUser(c)
if !user.Admin {
errorOutAnnoying(c, errors.New("Non-admin user tried to access admin endpoint."))
c.Abort()
return
}
c.Next()
}
func apiRequired(c *gin.Context) {
c.Next()
}