-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
57 lines (48 loc) · 1.39 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
package main
import (
"airqo-integrator/db"
"airqo-integrator/models"
"encoding/base64"
"github.com/gin-gonic/gin"
"strings"
)
func BasicAuth() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("dbConn", db.GetDB())
auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
RespondWithError(401, "Unauthorized", c)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !AuthenticateUser(pair[0], pair[1]) {
RespondWithError(401, "Unauthorized", c)
// c.Writer.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
return
}
c.Next()
}
}
func AuthenticateUser(username, password string) bool {
// log.Printf("Username:%s, password:%s", username, password)
userObj := models.User{}
err := db.GetDB().QueryRowx(
`SELECT
id, username, firstname, lastname , telephone, email
FROM users
WHERE
username = $1 AND password = crypt($2, password)`,
username, password).StructScan(&userObj)
if err != nil {
// fmt.Printf("User:[%v]", err)
return false
}
// fmt.Printf("User:[%v]", userObj)
return true
}
func RespondWithError(code int, message string, c *gin.Context) {
resp := map[string]string{"error": message}
c.JSON(code, resp)
c.Abort()
}