/
Profile.go
66 lines (53 loc) · 1.72 KB
/
Profile.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
package main
import (
"log" // Logs
"net" // Server logic
"net/http" // Server logic
"time" // Timing
// Database
"context"
"go.mongodb.org/mongo-driver/bson"
)
// Profile handles GET request for profile page
func Profile(w http.ResponseWriter, r *http.Request) {
// Checking credentials
// If user is not logged in, redirect to start page
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Println("/profile: Cannot discover user's IP")
ErrorHandler(w, r, http.StatusInternalServerError)
return
}
userCredential := Credential{
UserIP: net.ParseIP(ip),
}
if userCredential.UserIP == nil {
log.Println("/profile: Cannot discover user's IP")
ErrorHandler(w, r, http.StatusInternalServerError)
return
}
credentialsCollection := client.Database("Judex").Collection("credentials")
filter := bson.D{{Key: "userip", Value: userCredential.UserIP}}
err = credentialsCollection.FindOne(context.TODO(), filter).Decode(&userCredential)
if err == nil {
if time.Now().After(userCredential.EndTime) {
http.Redirect(w, r, "/", http.StatusSeeOther)
credentialsCollection.DeleteMany(context.TODO(), filter)
return
}
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// Looking for user information
usersCollection := client.Database("Judex").Collection("users")
var findResult User
filter = bson.D{{Key: "username", Value: userCredential.Username}}
err = usersCollection.FindOne(context.TODO(), filter).Decode(&findResult)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Executing template
if err := templates.ExecuteTemplate(w, "profile.html", findResult); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}