public virtual async Task <JsonResult> Get()
        {
            var result = await _service.GetAllAsync();

            if (result == null)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01003),
                                         StatusCodes.Status404NotFound));
            }

            return(new JsonAPIResult(result, StatusCodes.Status200OK));
        }
Esempio n. 2
0
        public JsonResult Get()
        {
            var result = _service.GetUserList();

            if (result == null)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01002),
                                         StatusCodes.Status404NotFound));
            }

            return(new JsonAPIResult(result, StatusCodes.Status200OK));
        }
        public async Task <JsonResult> Register([FromBody] UserRegisterVM model)
        {
            if (!ModelState.IsValid)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithModelState(modelStateDictionary: ModelState),
                                         StatusCodes.Status400BadRequest));
            }

            User entity = _mapper.Map <UserRegisterVM, User>(model);

            entity.Id             = Guid.NewGuid();
            entity.CreateDateTime = DateTime.UtcNow;

            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Sub, entity.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, entity.UserName),
                new Claim("UserId", entity.Id.ToString())
            };

            TokenCacheVM authData = new TokenCacheVM();

            authData.AccessToken            = _tokenService.GenerateAccessToken(claims);
            authData.RefreshToken           = _tokenService.GenerateRefreshToken();
            authData.AccessTokenExpiryTime  = new JwtSecurityTokenHandler().ReadToken(authData.AccessToken)?.ValidTo ?? DateTime.MinValue;
            authData.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(1);
            authData.Id = entity.Id;

            var identityResult = await _userManager.CreateAsync(entity, model.Password);

            if (!identityResult.Succeeded)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithIdentityErrors(errors: identityResult.Errors),
                                         StatusCodes.Status422UnprocessableEntity));
            }

            TimeSpan expiryTimeSpan = TimeSpan.FromSeconds(_tokenService.GetTokenExpiryDuration());
            var      cacheResult    = _tokenService.Redis.Insert(authData, expiryTimeSpan);

            if (!cacheResult.IsSuccessful)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01011),
                                         StatusCodes.Status409Conflict));
            }

            await _signInManager.SignInAsync(entity, isPersistent : false);

            UserAuthenticationVM returnVM = new UserAuthenticationVM();

            returnVM           = _mapper.Map <User, UserAuthenticationVM>(entity);
            returnVM.TokenData = authData;

            return(new JsonAPIResult(_apiResult.CreateVMWithRec <UserAuthenticationVM>(returnVM, entity.Id, true),
                                     StatusCodes.Status201Created));
        }
        public JsonResult Get([FromQuery] string key)
        {
            if (key == null || key == "" || key.Length < 4)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01003),
                                         StatusCodes.Status400BadRequest));
            }

            var messages = _service.Query().Where(s => s.Text.Contains(key));

            if (messages == null)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01002),
                                         StatusCodes.Status404NotFound));
            }

            var result = _mapper.ProjectTo <MessageVM>(messages).ToList();

            return(new JsonAPIResult(result, StatusCodes.Status200OK));
        }
Esempio n. 5
0
        public virtual async Task <IAPIResultVM> UpdateAsync(Guid id, U model, Guid?userId = null, bool isCommit = true)
        {
            try
            {
                Guid _userId = userId == null ? Guid.Empty : userId.Value;

                D entity = await _uow.Repository <D>().GetByIDAsync(id);

                if (entity.IsNull())
                {
                    return(_apiResult.CreateVMWithStatusCode(id, false, APIStatusCode.ERR01003));
                }

                entity = _mapper.Map <U, D>(model, entity);

                if (entity is ITableEntity)
                {
                    (entity as ITableEntity).UpdateBy = _userId;
                    (entity as ITableEntity).UpdateDT = DateTime.UtcNow;
                }

                Repository.Update(entity);

                if (isCommit)
                {
                    await CommitAsync();
                }

                return(_apiResult.CreateVMWithRec(entity, entity.Id, true));
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                return(_apiResult.CreateVM());
            }
        }
Esempio n. 6
0
        public async Task <JsonResult> Create([FromBody] UserLoginVM model)
        {
            if (!ModelState.IsValid)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithModelState(modelStateDictionary: ModelState),
                                         StatusCodes.Status400BadRequest));
            }

            var loginResult = await _signInManager.PasswordSignInAsync(model.UserName, model.Password,
                                                                       isPersistent : false, lockoutOnFailure : false);

            if (!loginResult.Succeeded)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01004),
                                         StatusCodes.Status404NotFound));
            }

            TimeSpan expiryTimeSpan;
            var      user = await _userManager.FindByNameAsync(model.UserName);

            var authData = _tokenService.Redis.GetById(user.Id);

            if (!authData.IsNull() && !authData.Id.IsEmptyGuid())
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02025),
                                         StatusCodes.Status400BadRequest));
            }

            if (authData == null || authData.AccessToken.IsNullOrEmptyString() || authData.AccessTokenExpiryTime < DateTime.UtcNow)
            {
                authData = new ViewModel.Auth.TokenCacheVM();

                var claims = new Claim[] {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                    new Claim("UserId", user.Id.ToString())
                };

                authData.AccessToken            = _tokenService.GenerateAccessToken(claims);
                authData.AccessTokenExpiryTime  = new JwtSecurityTokenHandler().ReadToken(authData.AccessToken)?.ValidTo ?? DateTime.MinValue;
                authData.RefreshToken           = _tokenService.GenerateRefreshToken();
                authData.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(1);
                authData.Id = user.Id;

                expiryTimeSpan = TimeSpan.FromTicks(authData.AccessTokenExpiryTime.Ticks - DateTime.UtcNow.Ticks);
            }
            else
            {
                expiryTimeSpan = TimeSpan.FromSeconds(_tokenService.GetTokenExpiryDuration());
            }

            var updateResult = _tokenService.Redis.Insert(authData, expiryTimeSpan);

            if (!updateResult.IsSuccessful)
            {
                return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01011),
                                         StatusCodes.Status409Conflict));
            }

            var returnVM = _mapper.Map <Domain.User, UserAuthenticationVM>(user);

            returnVM.TokenData = authData;

            SentrySdk.CaptureMessage($"User {user.UserName} is created an access token", SentryLevel.Info);
            return(new JsonAPIResult(returnVM, StatusCodes.Status200OK));
        }