1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5package main
6
7import (
8 "database/sql"
9 "fmt"
10 "os"
11 "syscall"
12
13 "git.sr.ht/~amolith/willow/users"
14 "golang.org/x/term"
15)
16
17// createUser is a CLI that creates a new user with the specified username
18func createUser(dbConn *sql.DB, username string) {
19 fmt.Println("Creating user", username)
20
21 fmt.Print("Enter password: ")
22 password, err := term.ReadPassword(int(syscall.Stdin))
23 if err != nil {
24 fmt.Println("Error reading password:", err)
25 os.Exit(1)
26 }
27 fmt.Println()
28
29 fmt.Print("Confirm password: ")
30 passwordConfirmation, err := term.ReadPassword(int(syscall.Stdin))
31 if err != nil {
32 fmt.Println("Error reading password confirmation:", err)
33 os.Exit(1)
34 }
35 fmt.Println()
36
37 if string(password) != string(passwordConfirmation) {
38 fmt.Println("Passwords do not match")
39 os.Exit(1)
40 }
41 err = users.Register(dbConn, username, string(password))
42 if err != nil {
43 fmt.Println("Error creating user:", err)
44 os.Exit(1)
45 }
46
47 fmt.Println("\nUser", username, "created successfully")
48 os.Exit(0)
49}
50
51// deleteUser is a CLI that deletes a user with the specified username
52func deleteUser(dbConn *sql.DB, username string) {
53 fmt.Println("Deleting user", username)
54 err := users.Delete(dbConn, username)
55 if err != nil {
56 fmt.Println("Error deleting user:", err)
57 os.Exit(1)
58 }
59
60 fmt.Printf("User %s deleted successfully\n", username)
61 os.Exit(0)
62}
63
64// listUsers is a CLI that lists all users in the database
65func listUsers(dbConn *sql.DB) {
66 fmt.Println("Listing all users")
67
68 dbUsers, err := users.GetUsers(dbConn)
69 if err != nil {
70 fmt.Println("Error retrieving users from the database:", err)
71 os.Exit(1)
72 }
73
74 if len(dbUsers) == 0 {
75 fmt.Println("- No users found")
76 } else {
77 for _, u := range dbUsers {
78 fmt.Println("-", u)
79 }
80 }
81 os.Exit(0)
82}
83
84// checkAuthorised is a CLI that checks whether the provided user/password
85// combo is authorised.
86func checkAuthorised(dbConn *sql.DB, username string) {
87 fmt.Printf("Checking whether password for user %s is correct\n", username)
88
89 fmt.Print("Enter password: ")
90 password, err := term.ReadPassword(int(syscall.Stdin))
91 if err != nil {
92 fmt.Println("Error reading password:", err)
93 os.Exit(1)
94 }
95 fmt.Println()
96
97 authorised, err := users.UserAuthorised(dbConn, username, string(password))
98 if err != nil {
99 fmt.Println("Error checking authorisation:", err)
100 os.Exit(1)
101 }
102
103 if authorised {
104 fmt.Println("User is authorised")
105 } else {
106 fmt.Println("User is not authorised")
107 }
108 os.Exit(0)
109}