aboutsummaryrefslogtreecommitdiff
path: root/go-src/user.go
blob: 78501c7c96d0b3931e2b1a9664f34902a9e4a5a9 (plain) (blame)
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
package ctfc

import (
	"bytes"
	"os"

	"gitlab.com/Syndamia/ctfc/go-src/folderPaths"
)

var loggedInUser User

type User struct {
	Username string
	Name     string
}

type UserProp int

const (
	passwordProp UserProp = iota + 1
	nameProp
)

func (u User) ValidatePassword(password string) bool {
	// TODO: Implement hashing
	f, _ := os.ReadFile(folderPaths.FileAtUsersFolder(u.Username))
	passHash := bytes.Split(f, []byte("\n"))[1]
	return string(passHash) == password
}

func (u User) updateProp(currentPassword string, newValue string, userProp UserProp) bool {
	if !u.ValidatePassword(currentPassword) {
		return false
	}
	var fileContents []byte

	switch userProp {
	case passwordProp:
		fileContents = []byte(u.Username + "\n" + newValue + "\n" + u.Name)
	case nameProp:
		fileContents = []byte(u.Username + "\n" + currentPassword + "\n" + newValue)
	default:
		return false
	}

	os.WriteFile(
		folderPaths.FileAtUsersFolder(u.Username),
		fileContents,
		0644)
	return true
}

func (u User) UpdatePassword(oldPassword string, newPassword string) bool {
	return u.updateProp(oldPassword, newPassword, passwordProp)
}

func (u User) UpdateName(password string, newName string) bool {
	return u.updateProp(password, newName, nameProp)
}

func logoutUser() {
	loggedInUser.Username = ""
	loggedInUser.Name = ""
}

func createUser(data []string) {
	// TODO: Password hashing
	f, _ := os.Create(folderPaths.FileAtUsersFolder(data[0]))
	f.WriteString(data[0] + "\n" + data[1] + "\n" + data[2])
	f.Close()
}

func logInUser(username string, password string) bool {
	if cu := getUser(username); cu.ValidatePassword(password) {
		loggedInUser = cu
		return true
	}
	return false
}

func getUser(username string) User {
	f, _ := os.ReadFile(folderPaths.FileAtUsersFolder(username))
	values := bytes.Split(f, []byte("\n"))
	return User{string(values[0]), string(values[2])}
}