/
main.go
175 lines (145 loc) · 3.79 KB
/
main.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"context"
"html/template"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/o1egl/paseto/v2"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var mongoClient *mongo.Client
type User struct {
Username string `bson:"username"`
Password string `bson:"password"`
}
func main() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
panic(err)
}
mongoClient = client
r := mux.NewRouter()
r.HandleFunc("/login", loginHandler).Methods("GET", "POST")
r.HandleFunc("/dashboard", dashboardHandler).Methods("GET")
r.HandleFunc("/logout", logoutHandler).Methods("POST")
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
user, err := findUser(r.FormValue("username"), r.FormValue("password"))
if err != nil {
http.Error(w, "Invalid login credentials", http.StatusUnauthorized)
return
}
token, err := generateToken(user.Username)
if err != nil {
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
return
}
expires := time.Now().Add(24 * time.Hour)
cookie := http.Cookie{
Name: "token",
Value: token,
Expires: expires,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/dashboard", http.StatusFound)
return
}
cookie, err := r.Cookie("token")
if err == nil && cookie.Value != "" {
http.Redirect(w, r, "/dashboard", http.StatusFound)
return
}
http.ServeFile(w, r, "login.html")
}
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("token")
if err != nil || cookie.Value == "" {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
username, err := getUsernameFromToken(cookie.Value)
if err != nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
tmpl, err := template.ParseFiles("dashboard.html")
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
data := struct {
Username string
}{
Username: username,
}
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{
Name: "token",
Value: "",
MaxAge: -1,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/login", http.StatusFound)
}
func findUser(username, password string) (*User, error) {
collection := mongoClient.Database("paseto").Collection("info")
var user User
filter := bson.M{"username": username, "password": password}
err := collection.FindOne(context.TODO(), filter).Decode(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func generateToken(username string) (string, error) {
secretKey := []byte("sirajaevents")
// PASETO v2
v2 := paseto.NewV2()
now := time.Now()
expiration := now.Add(24 * time.Hour)
// Membuat payload PASETO
claims := paseto.JSONToken{
Subject: username,
Issuer: "your_app_name",
Audience: "your_app_users",
Expiration: expiration,
}
// Membuat PASETO token
token, err := v2.Encrypt(secretKey, claims, nil)
if err != nil {
return "", err
}
return token, nil
}
func getUsernameFromToken(token string) (string, error) {
secretKey := []byte("sirajaevents")
// PASETO v2
v2 := paseto.NewV2()
var claims paseto.JSONToken
err := v2.Decrypt(token, secretKey, &claims, nil)
if err != nil {
return "", err
}
return claims.Subject, nil
}