Beispiel #1
0
        public async Task <IActionResult> Register([FromBody] RegisterDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Hay errores en validaciones", ModelState)));
            }
            if (string.Compare(model.Password.Trim(), model.ConfirmPassword.Trim()) != 0)
            {
                ModelState.AddModelError("Password", "El password y su confirmación no coinciden");
                return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Hay errores en validaciones", ModelState)));
            }
            using (var transaction = await _endContext.Database.BeginTransactionAsync())
            {
                try{
                    var endUserId = Guid.NewGuid().ToString();
                    var user      = new AppUser {
                        UserName = model.Email.Trim(), Email = model.Email.Trim(), EndUserId = endUserId
                    };
                    _userRepository.Create(
                        new EndUser
                    {
                        Id      = user.EndUserId,
                        Email   = model.Email.Trim(),
                        Name    = model.Name.Trim(),
                        Unicode = UnicodeGenerator.GetUnicode()
                    });
                    var result = await _userManager.CreateAsync(user, model.Password.Trim());

                    SecurityManager mgr = new SecurityManager(_jwtSettings, _userManager, _roleManager);
                    if (result.Succeeded)
                    {
                        //Add intoRole USERS
                        await _userManager.AddToRoleAsync(user, EndConstants.RoleNameForUsers);

                        _endContext.SaveChanges();
                        transaction.Commit();
                        await _signInManager.SignInAsync(user, false);

                        var authUser = await mgr.BuildAuthenticatedUserObject(user);

                        return(Ok(authUser));
                    }
                    else
                    {
                        var errors = result.Errors.Select(x => x.Description).ToList();
                        return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Identity validation errors", errors)));
                    }
                }catch (Exception ex) {
                    transaction.Rollback();
                    return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Exception, "Exception", ex)));
                }
            }
        }
Beispiel #2
0
        public async Task <IActionResult> Create([FromBody] AddUserDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Hay errores de validación", ModelState)));
            }
            using (var transaction = await _endContext.Database.BeginTransactionAsync())
            {
                try
                {
                    var enduser   = new EndUser();
                    var endUserId = Guid.NewGuid().ToString();
                    //create account
                    if (model.HasAccount)
                    {
                        AppUser existingUser = await _userManager.FindByEmailAsync(model.Email.Trim());

                        if (existingUser != null)
                        {
                            ModelState.AddModelError("Email", "El email está ocupado por otro usuario");
                            return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Validaciones", ModelState)));
                        }
                        if (string.IsNullOrEmpty(model.Email) || string.IsNullOrEmpty(model.Password))
                        {
                            ModelState.AddModelError("Email", "Email y Password son requeridos para crear la cuenta");
                            return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Validaciones", ModelState)));
                        }
                        if (model.Password.Trim().CompareTo(model.ConfirmPassword.Trim()) != 0)
                        {
                            ModelState.AddModelError("Password", "Password no coincide con la confirmación");
                            return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Validaciones", ModelState)));
                        }
                        var user = new AppUser {
                            UserName = model.Email.Trim(), Email = model.Email.Trim(), EndUserId = endUserId
                        };
                        var result = await _userManager.CreateAsync(user, model.Password.Trim());

                        _endContext.SaveChanges();    //Save user temp
                        if (result.Succeeded)
                        {
                            //Add intoRole USERS
                            await _userManager.AddToRoleAsync(user, EndConstants.RoleNameForUsers);

                            _endContext.SaveChanges();        //Add role to user temp
                        }
                        else
                        {
                            transaction.Rollback();
                            var errors = result.Errors.Select(x => x.Description).ToList();
                            return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Validation, "Identity validation errors", errors)));
                        }
                    }

                    //create user
                    enduser = new EndUser {
                        Id        = endUserId,
                        Name      = model.Name,
                        BirthDate = model.BirthDate,
                        Initial   = model.Initial,
                        Unicode   = UnicodeGenerator.GetUnicode(),
                        Email     = model.Email
                    };                               //Can repeat email in endUsers no in accounts
                    _userRepository.Create(enduser); //create user
                    _endContext.SaveChanges();
                    //follow
                    if (model.Followup)
                    {
                        AppUser currentUser = await _userManager.FindByNameAsync(User.Identity.Name);

                        var       permissionsFollowingStock = _followerPermissionRepository.GetStockPermissions();
                        var       followingId = Guid.NewGuid().ToString();
                        Following follow      = new Following {
                            Id                 = followingId,
                            CreatedAt          = DateTime.Now,
                            FollowedUserId     = enduser.Id,
                            FollowedById       = currentUser.EndUserId,
                            GrantedPermissions = GrantedFollowerPermissionFactory.Create(permissionsFollowingStock, true, followingId)
                        };

                        _userRepository.AddFollow(currentUser.EndUserId, follow);//Add followRequest
                        _endContext.SaveChanges();
                    }
                    transaction.Commit();
                    return(Ok(enduser));
                }
                catch (Exception ex) {
                    transaction.Rollback();
                    return(BadRequest(new ManagedErrorResponse(ManagedErrorCode.Exception, "Exception", ex)));
                }
            }
        }
Beispiel #3
0
 protected string RandomUnicodeOfLength(int length)
 {
     return(UnicodeGenerator.OfCodeUnitsLength(Random, length, length));
 }