-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
56 lines (43 loc) · 1.24 KB
/
auth.go
File metadata and controls
56 lines (43 loc) · 1.24 KB
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
package main
import(
"github.com/codegangsta/martini"
"net/http"
"encoding/base64"
"strings"
"code.google.com/p/go.crypto/bcrypt"
)
/*
Auth middel ware function for handling authentication and injecting User
*/
func Auth(c martini.Context, w http.ResponseWriter, r *http.Request){
auth := r.Header.Get("Authorization")
split := strings.SplitN(string(auth)," ",2)
if len(split) < 2 {
http.Error(w, "Unauthorized", 401)
}
data, err := base64.StdEncoding.DecodeString(split[1])
if err != nil {
http.Error(w, err.Error(), 500)
}
info := strings.SplitN(string(data),":",2)
if len(info) < 2 {
http.Error(w, "Unauthorized", 401)
}
u, _ := getloginuser(info[0])
crypterr := bcrypt.CompareHashAndPassword([]byte(u.Password),
[]byte(info[1]))
if crypterr != nil{
http.Error(w, "Unauthorized", 401)
}
user := User{ Username : u.Username, Email : u.Email, Role : u.Role }
c.Map(user)
}
/*
Admin middle ware function for handling admin check user after Auth
*/
func Admin(u User, w http.ResponseWriter, r *http.Request){
if u.Role != "admin"{
http.Error(w, http.StatusText(http.StatusForbidden),
http.StatusForbidden)
}
}