/// <summary>Initialises admin user and roles.</summary> /// <param name="scope">A limited DI Scope.</param> private async Task ConfigureDbAdminAndRoles(IServiceScope scope) { // Don't db.Database.Migrate here, slows server start time, do it on publish instead. var roleMan = scope.ServiceProvider.GetService <RoleManager <IdentityRole> >(); if (!roleMan.Roles.Any(r => r.Name == Roles.Admin)) { await roleMan.CreateAsync(new IdentityRole(Roles.Admin)); } if (!roleMan.Roles.Any(r => r.Name == Roles.EditGlobalData)) { await roleMan.CreateAsync(new IdentityRole(Roles.EditGlobalData)); } if (!roleMan.Roles.Any(r => r.Name == Roles.EditUserData)) { await roleMan.CreateAsync(new IdentityRole(Roles.EditUserData)); } var userManager = scope.ServiceProvider.GetService <UserManager <QbUser> >(); if (await userManager.FindByNameAsync("admin") == null) { var adminUser = new QbUser { UserName = "******", PhoneNumberConfirmed = true }; await userManager.CreateAsync(adminUser, "xxxxxxxx"); adminUser = await userManager.FindByNameAsync("admin"); await userManager.AddToRoleAsync(adminUser, Roles.Admin); } }
public async Task <IActionResult> Register(string username, string password, string phonenumber, [FromServices] ISmsSender smsSender, [FromServices] QbDbContext db) { var pars = new[] { username, password, phonenumber }; if (pars.Any(string.IsNullOrWhiteSpace)) { return(Res.JsonErrorResult("missing_field", 400, "One or more of required fields missing or empty: username, password, phonenumber.")); } var exists = null != await _userManager.FindByNameAsync(username); if (exists) { return(Res.JsonErrorResult("exists", 400, "Username already exists.")); } var user = new QbUser { UserName = username, PhoneNumberConfirmed = false }; var res = await _userManager.CreateAsync(user, password); if (res.Succeeded) { user = await _userManager.FindByNameAsync(username); // Creates a full user with all edit abilities for own information. var userGuid = new Guid(user.Id); // Create a Person with the same guid as the identity user. await CreatePerson(userGuid, db); var phoneToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phonenumber); // Ignore used for manual admin verified user. if (phonenumber.ToLowerInvariant() != "ignore") { if (!await smsSender.SendSms($"QB sign-up code:{phoneToken}", phonenumber)) { return (Res.JsonErrorResult("invalid_phone", 400, "User created but sms failed, try re-requesting code by changing phonenumber.")); } } return(Res.PlainUtf8($"User {username} successfully created, needs verification.")); } return(Res.JsonErrorResult("identity_error", 400, res.PrettyErrors())); }