public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            if (!await _reCaptcha.Verify(parameters.CaptchaResponse))
            {
                return(BadRequest());
            }

            var user = new ApplicationUser
            {
                UserName = parameters.UserName
            };

            var(isSuccess, error) = await _authorizator.CreateAsync(user, parameters.Password);

            if (!isSuccess)
            {
                return(BadRequest(error));
            }

            return(await Login(new LoginParameters
            {
                UserName = parameters.UserName,
                Password = parameters.Password
            }));
        }
Beispiel #2
0
        public async Task <UserInfo> Register(RegisterParameters registerParameters)
        {
            // Todo Handle StatusCodes??
            var result = await _httpClient.PostJsonAsync <UserInfo>("api/Authorize/Register", registerParameters);

            return(result);
        }
Beispiel #3
0
        public async Task <ClientApiResponse> Register(RegisterParameters registerParameters)
        {
            ClientApiResponse apiResponse = await _authorizeApi.Register(registerParameters);

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
            return(apiResponse);
        }
Beispiel #4
0
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                  .Select(error => error.ErrorMessage)
                                  .FirstOrDefault()));
            }

            var user = new ApplicationUser();

            user.UserName = parameters.UserName;
            var result = await _userManager.CreateAsync(user, parameters.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors.FirstOrDefault()?.Description));
            }

            return(await Login(new LoginParameters
            {
                UserName = parameters.UserName,
                Password = parameters.Password
            }));
        }
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                      .Select(error => error.ErrorMessage)
                                      .FirstOrDefault()));
                }

                // https://gooroo.io/GoorooTHINK/Article/17333/Custom-user-roles-and-rolebased-authorization-in-ASPNET-core/32835
                string[]       roleNames = { "SuperAdmin", "Admin", "User" };
                IdentityResult roleResult;

                foreach (var roleName in roleNames)
                {
                    //creating the roles and seeding them to the database
                    var roleExist = await _roleManager.RoleExistsAsync(roleName);

                    if (!roleExist)
                    {
                        roleResult = await _roleManager.CreateAsync(new IdentityRole <Guid>(roleName));
                    }
                }

                var user = new ApplicationUser
                {
                    UserName = parameters.UserName,
                    Email    = parameters.UserName
                };

                user.UserName = parameters.UserName;
                var result = await _userManager.CreateAsync(user, parameters.Password);

                if (!result.Succeeded)
                {
                    return(BadRequest(result.Errors.FirstOrDefault()?.Description));
                }

                //Role - Here we tie the new user to the "Admin" role
                await _userManager.AddToRoleAsync(user, "Admin");

                _logger.LogInformation("New user registered: {0}", user);

                return(await Login(new LoginParameters
                {
                    UserName = parameters.UserName,
                    Password = parameters.Password
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError("Register User Failed: {0}", ex.Message);
                return(BadRequest(ex));
            }
        }
Beispiel #6
0
        public async Task Register(RegisterParameters registerParameters)
        {
            var result = await _httpClient.PostAsJsonAsync("api/Authorize/Register", registerParameters);

            if (result.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new Exception(await result.Content.ReadAsStringAsync());
            }
            result.EnsureSuccessStatusCode();
        }
Beispiel #7
0
        public async Task Register(RegisterParameters registerParameters)
        {
            //var stringContent = new StringContent(JsonSerializer.Serialize(registerParameters), Encoding.UTF8, "application/json");
            var result = await _httpClient.PostAsJsonAsync("api/Authorize/Register", registerParameters);

            if (result.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new Exception(await result.Content.ReadAsStringAsync());
            }
            result.EnsureSuccessStatusCode();
        }
Beispiel #8
0
        public async Task <UserInfo> Register(RegisterParameters registerParameters)
        {
            RegisterInput input = new RegisterInput
            {
                UserName     = registerParameters.UserName,
                EmailAddress = registerParameters.Email,
                Password     = registerParameters.Password,
            };
            await _abpClient.Register(input);

            // Todo Handle StatusCodes??
            //var result = await _httpClient.PostJsonAsync<UserInfo>("api/Authorize/Register", registerParameters);
            //return result;
            return(null);
        }
Beispiel #9
0
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            //if (!ModelState.IsValid) return BadRequest(ModelState.Values.SelectMany(state => state.Errors)
            //                                                            .Select(error => error.ErrorMessage)
            //                                                            .FirstOrDefault());

            //var user = new ApplicationUser();
            //user.UserName = parameters.UserName;
            //var result = await _userManager.CreateAsync(user, parameters.Password);
            //if (!result.Succeeded) return BadRequest(result.Errors.FirstOrDefault()?.Description);

            //return await Login(new LoginParameters
            //{
            //    UserName = parameters.UserName,
            //    Password = parameters.Password
            //});
            return(Ok());
        }
Beispiel #10
0
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            var user = new ApplicationUser();

            user.UserName = parameters.UserName;
            var result = await _userManager.CreateAsync(user, parameters.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors.FirstOrDefault()?.Description));
            }

            return(await Login(new LoginParameters
            {
                UserName = parameters.UserName,
                Password = parameters.Password
            }));
        }
Beispiel #11
0
        public async Task <bool> CreateKorisnik(RegisterParameters registerParameters, Uloge uloga, int razredId = -1)
        {
            var user = new IdentityUser {
                UserName = registerParameters.Email, Email = registerParameters.Email
            };
            var result = await _userManager.CreateAsync(user, registerParameters.Password);

            //Add korisnik to the database
            _context.Add(new Korisnik
            {
                Ime          = registerParameters.Ime,
                Prezime      = registerParameters.Prezime,
                Spol         = registerParameters.Spol,
                EmailAdresa  = registerParameters.Email,
                DatumRođenja = registerParameters.DoB,
                User         = user,
                IdRazred     = razredId != -1 ? razredId : (int?)null
            });

            var userCreated = await _context.SaveChangesAsync(); //should be 1?

            //Get the createdUser id
            var newUserId = _context.Korisnik.First(k => k.EmailAdresa == registerParameters.Email).IdKorisnik;

            //Create KorisnikUloga with the User and Uloga pair
            var korisnikUloga = new KorisnikUloga {
                IdKorisnik = newUserId, IdUloga = (int)uloga
            };

            _context.Add(korisnikUloga);

            var ulogaCreated = await _context.SaveChangesAsync(); // should be 1?

            //Add the respected claims to the users for pages authentication and authorization
            var ulogaString = Enum.GetName(typeof(Uloge), uloga);
            await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, ulogaString));

            if (userCreated == 1 && ulogaCreated == 1)
            {
                return(true);
            }

            return(false);
        }
Beispiel #12
0
        public void TestInvalidRegister(ResourceId resource, RegisterParameters param, InvalidValue invalid)
        {
            var handler = new DefaultManager(CreateNewApiConnection());
            var request = GenerateRegisterRequest(ValidOperation.Put.ToString().ToLower());

            if (param == RegisterParameters.Id)
            {
                var tmpReq = new Dictionary <string, object>();
                InvalidValueMapper[invalid](tmpReq, param.GetEnumStringValue());
                request[RegisterParameters.Data.GetEnumStringValue()] = tmpReq;
            }
            else
            {
                InvalidValueMapper[invalid](request, param.GetEnumStringValue());
            }
            var response = handler.Send <object>($"{RegisterEndpoint}{resource.ToString().ToLower()}s", JsonConvert.SerializeObject(request), HttpMethod.POST, ContentType);

            Assert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest));
        }
Beispiel #13
0
        public async Task <ActionResult> GetSampleQuery([FromBody, Required] RegisterParameters registerParams)
        {
            try
            {
                await _dbContext.UserLogin.AddAsync(new UserLogin
                {
                    Email     = registerParams.Email,
                    Password  = registerParams.Password,
                    Username  = registerParams.Username,
                    FirstName = registerParams.FirstName,
                    LastName  = registerParams.LastName
                });

                await _dbContext.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(BadRequest());
            }

            return(Ok());
        }
Beispiel #14
0
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            var user = new ApplicationUser();

            user.UserName = parameters.UserName;
            var result = await _userManager.CreateAsync(user, parameters.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors.FirstOrDefault()?.Description));
            }

            var usr = await _userManager.FindByNameAsync(user.UserName);

            usr.Email       = parameters.Email;
            usr.PhoneNumber = parameters.Phone;
            await _userManager.UpdateAsync(usr);

            Athlete athlete;

            using (BookingsDBContext db = new BookingsDBContext())
            {
                athlete = new Athlete
                {
                    Id            = 0,
                    UserName      = user.UserName,
                    Email         = user.Email,
                    HasAccessCard = user.HasAccessCard,
                    IsAdmin       = user.IsAdmin,
                    IsCoach       = user.IsCoach,
                    PhoneNumber   = user.PhoneNumber
                };
                try
                {
                    await db.Athletes.AddAsync(athlete);

                    await db.SaveChangesAsync();

                    var athletes = db.Athletes.ToList();
                    athlete = athletes[0];
                    System.Diagnostics.Debug.WriteLine(athlete.Id);
                }
                catch (Microsoft.Data.Sqlite.SqliteException sqlEx)
                {
                    System.Diagnostics.Debug.WriteLine(sqlEx.Message);
                    System.Diagnostics.Debug.WriteLine(sqlEx.InnerException);
                }
            }
            System.Diagnostics.Debug.WriteLine(athlete.Id);
            //using (BookingsDBContext db2 = new BookingsDBContext())
            //{
            //    athlete.Id = 1;
            //    System.Diagnostics.Debug.WriteLine("====Doing Athlete mirror of user====");
            //    var booking = new BookingInfo
            //    {
            //        Id = 0,
            //        Date = new DateTime(2020, 2, 15),
            //        _Time = 12,
            //        _Duration = 2,
            //        Slot = 1,
            //        AthleteId = athlete.Id
            //    };
            //    System.Diagnostics.Debug.WriteLine("====Done Athlete mirror of user====");
            //    try
            //    {
            //       // db2.Attach<BookingInfo>(booking);
            //        System.Diagnostics.Debug.WriteLine("====Doing Booking mirror db - 2====");
            //        await db2.BookingInfo.AddAsync(booking);
            //        System.Diagnostics.Debug.WriteLine("====Doing Booking mirror db - 3====");
            //        await db2.SaveChangesAsync();
            //        System.Diagnostics.Debug.WriteLine("====Doing Booking mirror db - 4r====");
            //    }
            //    catch (Microsoft.Data.Sqlite.SqliteException sqlEx)
            //    {
            //        System.Diagnostics.Debug.WriteLine("====Doing Athlete mirror db Error");
            //        System.Diagnostics.Debug.WriteLine(sqlEx.Message);
            //        System.Diagnostics.Debug.WriteLine(sqlEx.InnerException);
            //    }
            //    catch (Exception Ex)
            //    {
            //        System.Diagnostics.Debug.WriteLine("====Doing Athlete mirror db Error");
            //        System.Diagnostics.Debug.WriteLine(Ex.Message);
            //        System.Diagnostics.Debug.WriteLine(Ex.InnerException);
            //    }
            //}



            return(await Login(new LoginParameters
            {
                UserName = parameters.UserName,
                Password = parameters.Password
            }));
        }
        public virtual async Task Register(RegisterParameters registerParameters)
        {
            await _authorizeApi.Register(registerParameters);

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
Beispiel #16
0
        public async Task Register(RegisterParameters registerParameters)
        {
            _userInfoCache = await _authorizeApi.Register(registerParameters);

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
 public async Task Register(RegisterParameters registerParameters)
 {
     userInfo = await _authorizeApi.Register(registerParameters);
 }
 public async Task <ClientApiResponse> Register(RegisterParameters registerParameters)
 {
     return(await _httpClient.PostJsonAsync <ClientApiResponse>("api/Authorize/Register", registerParameters));
 }
        public async Task <IActionResult> Register(RegisterParameters parameters)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                      .Select(error => error.ErrorMessage)
                                      .FirstOrDefault()));
                }

                // https://gooroo.io/GoorooTHINK/Article/17333/Custom-user-roles-and-rolebased-authorization-in-ASPNET-core/32835
                string[]       roleNames = { "SuperAdmin", "Admin", "User" };
                IdentityResult roleResult;

                foreach (var roleName in roleNames)
                {
                    //creating the roles and seeding them to the database
                    var roleExist = await _roleManager.RoleExistsAsync(roleName);

                    if (!roleExist)
                    {
                        roleResult = await _roleManager.CreateAsync(new IdentityRole <Guid>(roleName));
                    }
                }

                var user = new ApplicationUser
                {
                    UserName = parameters.UserName,
                    Email    = parameters.Email
                };

                user.UserName = parameters.UserName;
                var result = await _userManager.CreateAsync(user, parameters.Password);

                if (!result.Succeeded)
                {
                    return(BadRequest(result.Errors.FirstOrDefault()?.Description));
                }

                //Role - Here we tie the new user to the "Admin" role
                await _userManager.AddToRoleAsync(user, "Admin");

                if (Convert.ToBoolean(_configuration["RequireConfirmedEmail"]))
                {
                    #region New  User Confirmation Email
                    try
                    {
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["ApplicationUrl"], user.Id, token);

                        var email = new EmailMessage();
                        email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
                        email.FromAddresses.Add(new EmailAddress("*****@*****.**", "*****@*****.**"));
                        email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form

                        _logger.LogInformation("New user registered: {0}", user);
                        await _emailService.SendEmailAsync(email);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation("New user email failed: {0}", ex.Message);
                    }
                    #endregion
                    return(Ok(new { success = "true" }));
                }

                #region New  User Email
                try
                {
                    var email = new EmailMessage();
                    email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
                    email.FromAddresses.Add(new EmailAddress("*****@*****.**", "*****@*****.**"));
                    email = EmailTemplates.BuildNewUserEmail(email, user.UserName, user.Email, parameters.Password); //Replace First UserName with Name if you want to add name to Registration Form

                    _logger.LogInformation("New user registered: {0}", user);
                    await _emailService.SendEmailAsync(email);
                }
                catch (Exception ex)
                {
                    _logger.LogInformation("New user email failed: {0}", ex.Message);
                }
                #endregion

                return(await Login(new LoginParameters
                {
                    UserName = parameters.UserName,
                    Password = parameters.Password
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError("Register User Failed: {0}", ex.Message);
                return(BadRequest(ex));
            }
        }
        public void TestValidDuplicateRegister(ResourceId resource, Enums.ValidDuplicated dup, RegisterParameters param)
        {
            var handler  = new DefaultManager(CreateNewApiConnection());
            var request  = DuplicateValues[dup]()[param.GetEnumStringValue()];
            var response = handler.Send <object>($"{RegisterEndpoint}{resource.ToString().ToLower()}s", request, HttpMethod.POST, ContentType);

            Assert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent));
        }
 public async Task Register(RegisterParameters registerParameters)
 {
     await _httpClient.PostJsonAsync <UserInfo>("api/Authorize/Register", registerParameters);
 }
        public async Task Register(RegisterParameters registerParameters)
        {
            userInfo = await _authorizeApi.Register(registerParameters);

            NotifyAuthenticationStateChanged();
        }