-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.go
95 lines (82 loc) · 2.1 KB
/
login.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
package main
import (
"fmt"
"net/http"
"strings"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
var userkey = "user"
func AuthRequired(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(userkey)
if user == nil {
c.Redirect(http.StatusSeeOther, "/login")
c.Abort()
}
c.Next()
}
func AdminRequired(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(userkey)
if user == nil {
c.Redirect(http.StatusSeeOther, "/login")
c.Abort()
} else {
if !isAdmin(user.(string)) {
c.Redirect(http.StatusSeeOther, "/")
c.Abort()
}
}
c.Next()
}
func isAdmin(userName string) bool {
for _, admin := range codyConf.VCloudAdmin {
if userName == admin {
return true
}
}
return false
}
// 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")
// Validate form input
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.HTML(http.StatusBadRequest, "login.html", gin.H{"error": "Username or password can't be empty 🙄"})
return
}
// FETCH FROM IALAB lol
err := vcloudAuth(username, password)
if err != nil {
c.HTML(http.StatusBadRequest, "login.html", gin.H{"error": "Incorrect username or password."})
return
}
// Save the username in the session
session.Set(userkey, username)
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.Redirect(http.StatusSeeOther, "/")
}
func getUser(c *gin.Context) string {
session := sessions.Default(c)
return fmt.Sprintf("%s", session.Get(userkey))
}
func logout(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(userkey)
if user == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
return
}
session.Delete(userkey)
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.Redirect(http.StatusSeeOther, "/login")
}