aboutsummaryrefslogtreecommitdiff
path: root/VNLib.Plugins.Essentials.Accounts/AccountsEntryPoint.cs
blob: ed7947682c30bdaa88d0e619ba3eb0cb95430620 (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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
* Copyright (c) 2022 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Accounts
* File: AccountsEntryPoint.cs 
*
* AccountsEntryPoint.cs is part of VNLib.Plugins.Essentials.Accounts which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Accounts is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials.Accounts is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Linq;
using System.Collections.Generic;

using VNLib.Utils.Memory;
using VNLib.Utils.Logging;
using VNLib.Plugins.Essentials.Users;
using VNLib.Plugins.Essentials.Accounts.Endpoints;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Users;
using VNLib.Plugins.Extensions.Loading.Routing;

namespace VNLib.Plugins.Essentials.Accounts
{
    public sealed class AccountsEntryPoint : PluginBase
    {

        public override string PluginName => "Essentials.Accounts";

        protected override void OnLoad()
        {
            try
            {
                //Route endpoints
                this.Route<LoginEndpoint>();

                this.Route<LogoutEndpoint>();

                this.Route<KeepAliveEndpoint>();

                this.Route<ProfileEndpoint>();

                this.Route<PasswordChangeEndpoint>();

                this.Route<MFAEndpoint>();

                //Write loaded to log
                Log.Information("Plugin loaded");
            }
            catch (KeyNotFoundException knf)
            {
                Log.Error("Missing required account configuration variables {mess}", knf.Message);
            }
            catch (UriFormatException uri)
            {
                Log.Error("Invalid endpoint URI {message}", uri.Message);
            }
        }

     

        protected override void OnUnLoad()
        {
            //Write closing messsage and dispose the log
            Log.Information("Plugin unloaded");
        }
      
        protected override async void ProcessHostCommand(string cmd)
        {
            //Only process commands if the plugin is in debug mode
            if (!this.IsDebug())
            {
                return;
            }
            try
            {
                IUserManager Users = this.GetUserManager();
                PasswordHashing Passwords = this.GetPasswords();

                //get args as a list
                List<string> args = cmd.Split(' ').ToList();
                if (args.Count < 3)
                {
                    Log.Warn("No command specified");
                }
                switch (args[2].ToLower())
                {
                    //Create new user
                    case "create":
                        {
                            int uid = args.IndexOf("-u");
                            int pwd = args.IndexOf("-p");
                            if (uid < 0 || pwd < 0)
                            {
                                Log.Warn("You are missing required argument values. Format 'create -u <username> -p <password>'");
                                return;
                            }
                            string username = args[uid + 1].Trim();
                            string randomUserId = AccountManager.GetRandomUserId();
                            //Password as privatestring DANGEROUS to refs
                            using (PrivateString password = (PrivateString)args[pwd + 1].Trim()!)
                            {
                                //Hash the password
                                using PrivateString passHash = Passwords.Hash(password);
                                //Create the user
                                using IUser user = await Users.CreateUserAsync(randomUserId, username, AccountManager.MINIMUM_LEVEL, passHash);                                
                                //Set active flag
                                user.Status = UserStatus.Active;
                                //Set local account
                                user.SetAccountOrigin(AccountManager.LOCAL_ACCOUNT_ORIGIN);

                                await user.ReleaseAsync();
                            }
                            Log.Information("Successfully created user {id}", username);

                        }
                        break;
                    case "reset":
                        {
                            int uid = args.IndexOf("-u");
                            int pwd = args.IndexOf("-p");
                            if (uid < 0 || pwd < 0)
                            {
                                Log.Warn("You are missing required argument values. Format 'reset -u <username> -p <password>'");
                                return;
                            }
                            string username = args[uid + 1].Trim();
                            //Password as privatestring DANGEROUS to refs
                            using (PrivateString password = (PrivateString)args[pwd + 1].Trim()!)
                            {
                                //Hash the password
                                using PrivateString passHash = Passwords.Hash(password);
                                //Get the user
                                using IUser? user = await Users.GetUserFromEmailAsync(username);

                                if(user == null)
                                {
                                    Log.Warn("The specified user does not exist");
                                    break;
                                }
                                
                                //Set the password
                                await Users.UpdatePassAsync(user, passHash);
                            }
                            Log.Information("Successfully reset password for {id}", username);
                        }
                        break;
                    case "delete":
                        {
                            //get user-id
                            string userId = args[3].Trim();
                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(userId);
                            
                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }
                            
                            //delete user
                            user.Delete();
                            //Release user
                            await user.ReleaseAsync();
                        }
                        break;
                    default:
                        Log.Warn("Uknown command");
                        break;
                }
            }
            catch (UserExistsException)
            {
                Log.Error("User already exists");
            }
            catch(UserCreationFailedException)
            {
                Log.Error("Failed to create the new user");
            }
            catch (ArgumentOutOfRangeException)
            {
                Log.Error("You are missing required command arguments");
            }
            catch(Exception ex)
            {
                Log.Error(ex);    
            }
        }
    }
}