summaryrefslogtreecommitdiff
blob: d06a2d7c81dae00359975dbda23b6b4a63999a4c (plain)
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
package utils

import (
	"glsamaker/pkg/app/handler/authentication/auth_session"
	"glsamaker/pkg/database/connection"
	"glsamaker/pkg/models/users"
	"net/http"
	"strings"
)

// utility methods to check whether a user is authenticated

func Only2FAMissing(w http.ResponseWriter, r *http.Request) bool {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	return err == nil && sessionID != nil && auth_session.Only2FAMissing(sessionID.Value, userIP)
}

func IsAuthenticated(w http.ResponseWriter, r *http.Request) bool {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	return err == nil && sessionID != nil && auth_session.IsLoggedIn(sessionID.Value, userIP)
}

func IsAuthenticatedAndNeedsNewPassword(w http.ResponseWriter, r *http.Request) bool {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	return err == nil && sessionID != nil && auth_session.IsLoggedInAndNeedsNewPassword(sessionID.Value, userIP)
}

func IsAuthenticatedAndNeeds2FA(w http.ResponseWriter, r *http.Request) bool {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	return err == nil && sessionID != nil && auth_session.IsLoggedInAndNeeds2FA(sessionID.Value, userIP)
}

func IsAuthenticatedAsAdmin(w http.ResponseWriter, r *http.Request) bool {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	if err != nil || sessionID == nil || !auth_session.IsLoggedIn(sessionID.Value, userIP) {
		return false
	}

	user := GetAuthenticatedUser(r)

	return user != nil && user.Permissions.Admin.View

}

func GetAuthenticatedUser(r *http.Request) *users.User {
	sessionID, err := r.Cookie("session")
	userIP := getIP(r)

	if err != nil || sessionID == nil || !(auth_session.IsLoggedIn(sessionID.Value, userIP) || auth_session.Only2FAMissing(sessionID.Value, userIP)) {
		return nil
	}

	userId := auth_session.GetUserId(sessionID.Value, userIP)

	user := &users.User{Id: userId}
	err = connection.DB.Select(user)

	if err != nil {
		return nil
	}

	return user
}

func getIP(r *http.Request) string {
	forwarded := r.Header.Get("X-FORWARDED-FOR")
	if forwarded != "" {
		return strings.Split(forwarded, ":")[0]
	}
	return strings.Split(r.RemoteAddr, ":")[0]
}