Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
CreateUser.cs
1using System;
2using System.Collections.Generic;
3using System.Text.RegularExpressions;
4using System.Threading.Tasks;
5using Waher.Content;
8using Waher.Script;
11
13{
17 public class CreateUser : CommandRegEx
18 {
22 public CreateUser()
23 : base(@"^create\s+user\s+(?'Name'[^\s]+)\s+(?'Roles'[^\s\{\}]+(\s+[^\s\{\}]+)*)(\s+(?'MetaData'\{[^\}]*\})(\s+(?'Password'[^\s]+))?)?$")
24 {
25 }
26
30 public override string Name => "Create";
31
40 public override async Task Execute(ChatState State, string[] Arguments, string OrgMessage, Match Details,
41 ResponseCallbackHandler ResponseCallback)
42 {
43 string Name = Details.Groups["Name"].Value;
44 string[] RoleIds = Details.Groups["Roles"].Value.Split(CommonTypes.WhiteSpace, System.StringSplitOptions.RemoveEmptyEntries);
45 string MetaDataStr = Details.Groups["MetaData"].Value;
46 string Password = Details.Groups["Password"].Value;
47
49 if (!(User is null))
50 throw new Exception("User already exists.");
51
52 foreach (string RoleId in RoleIds)
53 {
54 Role _ = await Waher.Security.Users.Roles.GetRole(RoleId, false)
55 ?? throw new Exception("Role `" + RoleId + "` does not exist.");
56 }
57
58 List<UserMetaData> MetaData = new List<UserMetaData>();
59
60 if (!string.IsNullOrEmpty(MetaDataStr))
61 {
62 Expression Exp = new Expression(MetaDataStr);
63 object Result = await Exp.EvaluateAsync(HttpServer.CreateVariables());
64 if (Result is IDictionary<string, object> Obj)
65 {
66 foreach (KeyValuePair<string, object> P in Obj)
67 {
68 MetaData.Add(new UserMetaData()
69 {
70 Name = P.Key,
71 Value = P.Value?.ToString() ?? string.Empty
72 });
73 }
74 };
75 }
76
77 if (string.IsNullOrEmpty(Password))
78 {
79 Password = Base64Url.Encode(Gateway.NextBytes(32));
80 await ResponseCallback("Generating password: `" + Password + "`", string.Empty);
81 }
82 else if (Password.Length < 16)
83 throw new Exception("Password too short.");
84
85 User NewUser = new User()
86 {
87 UserName = Name,
88 RoleIds = RoleIds,
89 MetaData = MetaData.ToArray(),
90 PasswordHash = Convert.ToBase64String(Waher.Security.Users.Users.ComputeHash(Name, Password))
91 };
92
93 await Persistence.Database.Insert(NewUser);
94
96
97 await ResponseCallback("User created: `" + Name + "`", string.Empty);
98 }
99
104 public override HelpItem[] GetHelp()
105 {
106 return new HelpItem[]
107 {
108 new HelpItem("create user NAME ROLES[ METADATA[ PASSWORD]]", "Creates a new user with the user name given by `NAME` and privileges defined by `ROLES`. `ROLES` is one or more roles separated by whitespace. `METADATA` is an object-exnihilo definition of meta-data associated with the user. `PASSWORD` is an optional password string to assign to the user account. If not provided, a random password is provided.")
109 };
110 }
111 }
112}
Static class that does BASE64URL encoding (using URL and filename safe alphabet), as defined in RFC46...
Definition: Base64Url.cs:11
static string Encode(byte[] Data)
Converts a binary block of data to a Base64URL-encoded string.
Definition: Base64Url.cs:48
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
static readonly char[] WhiteSpace
Contains white-space characters.
Definition: CommonTypes.cs:33
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static byte[] NextBytes(int NrBytes)
Generates an array of random bytes.
Definition: Gateway.cs:3534
Implements an HTTP server.
Definition: HttpServer.cs:36
static Variables CreateVariables()
Creates a new collection of variables, that contains access to the global set of variables.
Definition: HttpServer.cs:1604
Class managing a script expression.
Definition: Expression.cs:39
async Task< object > EvaluateAsync(Variables Variables)
Evaluates the expression, using the variables provided in the Variables collection....
Definition: Expression.cs:4275
Corresponds to a role in the system.
Definition: Role.cs:15
Maintains the collection of all roles in the system.
Definition: Roles.cs:14
static Task< Role > GetRole(string RoleId)
Gets the Role object corresponding to a Role ID.
Definition: Roles.cs:23
Corresponds to a user in the system.
Definition: User.cs:21
Contains a piece of meta-data information about a user.
Definition: UserMetaData.cs:11
Maintains the collection of all users in the system.
Definition: Users.cs:24
static byte[] ComputeHash(string UserName, string Password)
Computes a hash of a password.
Definition: Users.cs:157
static async Task< User > GetUser(string UserName, bool CreateIfNew)
Gets the User object corresponding to a User Name.
Definition: Users.cs:65
static void ClearCache()
Clears internal caches.
Definition: Users.cs:202
An administrative command whose syntax is validated with a regular expression.
Definition: CommandRegEx.cs:12
Contains an item of information about a command.
Definition: HelpItem.cs:9
override async Task Execute(ChatState State, string[] Arguments, string OrgMessage, Match Details, ResponseCallbackHandler ResponseCallback)
Executes the command.
Definition: CreateUser.cs:40
override HelpItem[] GetHelp()
Gets help about the command.
Definition: CreateUser.cs:104
Basic interface for a user.
Definition: IUser.cs:7
delegate Task< string > ResponseCallbackHandler(string Markdown, string MessageId)
Delegate for response callback handler methods.
Definition: App.xaml.cs:4