Пример #1
0
        public async Task <IActionResult> Add([FromBody] ClipboardAddBindingModel collection)
        {
            try {
                var model = _mapper.Map <ClipboardAddSchema>(collection);

                var query = new ClipboardGetFirstSchema {
                    AccountId = CurrentAccount.Id,
                    Content   = model.Content
                };
                var duplicated = await _clipboardService.FirstAsync(query).ConfigureAwait(true);

                if (duplicated == null)
                {
                    await _clipboardService.AddAsync(model).ConfigureAwait(true);

                    return(Ok());
                }

                return(BadRequest(_localizer[DataTransferer.DuplicatedValueFound().Message]));
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem());
            }
        }
 public async Task <IActionResult> SigninConfirmationAsync()
 {
     try {
         return(Ok());
     }
     catch (Exception ex) {
         Log.Error(ex, ex.Source);
         return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
     }
 }
Пример #3
0
        public async Task <IServiceResult> SignupAsync(SignupBindingModel signupModel)
        {
            var username   = _randomMaker.NewNumber();
            var duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });

            while (duplicated != null)
            {
                username   = _randomMaker.NewNumber();
                duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });
            }

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try {
                    var now = DateTime.UtcNow;

                    var account = new AccountAddSchema {
                        Password   = _cryptograph.RNG(signupModel.Password),
                        ProviderId = AccountProvider.Clipboardy.ToInt(),
                        Username   = username,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var accountId = await AddAsync(account);

                    var accountDevice = new AccountDeviceAddSchema {
                        AccountId  = accountId,
                        DeviceId   = signupModel.DeviceId,
                        DeviceName = signupModel.DeviceName,
                        DeviceType = signupModel.DeviceType,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var deviceId = await _accountDeviceService.AddAsync(accountDevice);

                    var accountProfile = new AccountProfileAddSchema {
                        AccountId = accountId,
                        LinkedId  = string.IsNullOrWhiteSpace(signupModel.Email) ? signupModel.Phone : signupModel.Email,
                        TypeId    = string.IsNullOrWhiteSpace(signupModel.Email) ? AccountProfileType.Phone.ToInt() : AccountProfileType.Email.ToInt(),
                        CreatedAt = now,
                        StatusId  = Status.Active.ToInt()
                    };
                    await _accountProfileService.AddAsync(accountProfile);

                    transaction.Complete();

                    var token = _jwtHandler.Bearer(new Account(accountId, deviceId, username, now).ToClaimsIdentity());
                    return(DataTransferer.Ok(token));
                }
                catch (Exception ex) {
                    var errmsg = "Something went wrong.";
                    Log.Error(ex, errmsg);
                    return(DataTransferer.InternalServerError(ex));
                }
            }
        }
Пример #4
0
        public async Task <IServiceResult> ExternalSignupAsync(ExternalUserBindingModel externalUser)
        {
            var username   = _randomMaker.NewNumber();
            var duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });

            while (duplicated != null)
            {
                username   = _randomMaker.NewNumber();
                duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });
            }

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try {
                    var now = DateTime.UtcNow;

                    var account = new AccountAddSchema {
                        ProviderId = externalUser.ProviderId.ToInt(),
                        Username   = username,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var accountId = await AddAsync(account);

                    var accountDevice = new AccountDeviceAddSchema {
                        AccountId  = accountId,
                        DeviceId   = externalUser.DeviceId,
                        DeviceName = externalUser.DeviceName,
                        DeviceType = externalUser.DeviceType,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var deviceId = await _accountDeviceService.AddAsync(accountDevice);

                    var accountProfile = new AccountProfileAddSchema {
                        AccountId = accountId,
                        TypeId    = AccountProfileType.Email.ToInt(),
                        LinkedId  = externalUser.Email,
                        CreatedAt = now,
                        StatusId  = Status.Active.ToInt()
                    };
                    await _accountProfileService.AddAsync(accountProfile);

                    transaction.Complete();
                    var token = _jwtHandler.Bearer(new Account(accountId, deviceId, username, now).ToClaimsIdentity());
                    return(DataTransferer.Ok(token));
                }
                catch (Exception ex) {
                    var errmsg = "Something went wrong.";
                    Log.Error(ex, errmsg);
                    return(null);
                }
            }
        }
Пример #5
0
        public async Task <IActionResult> ChangePasswordRequestedAsync([FromQuery] string username, [FromQuery] string token)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(token))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
            }

            var result = new ChangeForgotenPasswordViewModel {
                Username = Encoding.UTF8.GetString(Convert.FromBase64String(username)),
                Token    = token
            };
            await Task.CompletedTask.ConfigureAwait(true);

            return(Ok(result));
        }
Пример #6
0
        public async Task <IActionResult> ChangePasswordAsync([FromBody] ChangePasswordBindingModel collection)
        {
            Log.Debug($"ChangePassword => {JsonConvert.SerializeObject(collection)}");

            try {
                if (string.IsNullOrEmpty(collection?.Password) || string.IsNullOrEmpty(collection.NewPassword) || string.IsNullOrEmpty(collection.ConfirmPassword))
                {
                    return(BadRequest(_localizer[DataTransferer.DefectivePassword().Message]));
                }

                if (collection.NewPassword != collection.ConfirmPassword)
                {
                    return(BadRequest(_localizer[DataTransferer.PasswordsMissmatch().Message]));
                }

                var account = await _accountService.FirstAsync(new AccountGetFirstSchema {
                    Id = CurrentAccount.Id
                }).ConfigureAwait(true);

                if (account == null)
                {
                    return(BadRequest(_localizer[DataTransferer.UserNotFound().Message]));
                }

                if (_cryptograph.IsEqual(collection.Password, account.Password))
                {
                    await _accountService.UpdateAsync(new AccountUpdateSchema {
                        Id       = account.Id.Value,
                        Password = _cryptograph.RNG(collection.NewPassword)
                    }).ConfigureAwait(false);

                    return(Ok(_localizer[DataTransferer.PasswordChanged().Message]));
                }
                else
                {
                    return(Unauthorized(_localizer[DataTransferer.WrongPassword().Message]));
                }
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }
Пример #7
0
        public async Task <IActionResult> SigninAsync([FromBody] SigninBindingModel collection)
        {
            Log.Debug($"A User is trying to signing in with this data: {JsonConvert.SerializeObject(collection)}");

            if (string.IsNullOrEmpty(collection?.Username) || string.IsNullOrEmpty(collection?.Password))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveUsernameOrPassword().Message]));
            }

            var deviceHeader = GetDeviceInfosFromHeader();

            if (deviceHeader == null)
            {
                return(BadRequest(_localizer[DataTransferer.UnofficialRequest().Message]));
            }

            collection.DeviceId   = deviceHeader.DeviceId;
            collection.DeviceName = deviceHeader.DeviceName;
            collection.DeviceType = deviceHeader.DeviceType;

            try {
                var result = await _accountService.SigninAsync(collection).ConfigureAwait(true);

                switch (result.Code)
                {
                case 200:
                    return(Ok(result.Data));

                case 400:
                    return(BadRequest(result.Message));

                case 500:
                default:
                    return(Problem(result.Message));
                }
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }
        public async Task <IActionResult> Signin([FromQuery] string provider = "Google")
        {
            var deviceHeader = GetDeviceInfosFromHeader();

            if (deviceHeader == null)
            {
                return(BadRequest(DataTransferer.DefectiveEntry().Message));
            }

            var userdata    = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(deviceHeader)));
            var redirecturl = $"/api/externalauthentication/signincallback?userdata={userdata}";

            var authprops = new AuthenticationProperties {
                AllowRefresh = true,
                ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(7),
                IsPersistent = true,
                RedirectUri  = redirecturl
            };

            Response.Redirect(redirecturl);
            await Response.CompleteAsync().ConfigureAwait(true);

            return(Challenge(authprops, provider));
        }
        public async Task <IActionResult> SigninCallbackAsync(string userData = null, string remoteError = null)
        {
            try {
                if (string.IsNullOrWhiteSpace(userData))
                {
                    Log.Error("userData is not defined");
                    return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
                }

                var headerbindingmodel = JsonConvert.DeserializeObject <Device>(Encoding.UTF8.GetString(Convert.FromBase64String(userData)));
                if (headerbindingmodel == null ||
                    string.IsNullOrWhiteSpace(headerbindingmodel.DeviceId) ||
                    string.IsNullOrWhiteSpace(headerbindingmodel.DeviceName) ||
                    string.IsNullOrWhiteSpace(headerbindingmodel.DeviceType))
                {
                    Log.Error("userData is not valid");
                    return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
                }

                // read external identity from the temporary cookie
                var authenticationResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(true);

                if (!authenticationResult.Succeeded)
                {
                    Log.Error("External authentication failed");
                    return(Problem(_localizer[DataTransferer.ExternalAuthenticationFailed().Message]));
                }

                // retrieve claims of the external user
                var claimPrincipal = authenticationResult.Principal;
                if (claimPrincipal == null)
                {
                    Log.Error("External authentication user principal error");
                    return(Problem(_localizer[DataTransferer.ExternalAuthenticationUserError().Message]));
                }

                // transform claims list to model
                var externalUser = GetExternalUser(claimPrincipal.Claims);

                if (string.IsNullOrWhiteSpace(externalUser.Email))
                {
                    Log.Error("External authentication user email not found");
                    return(Problem(_localizer[DataTransferer.ExternalAuthenticationEmailError().Message]));
                }

                if (externalUser.ProviderId == AccountProvider.Clipboardy)
                {
                    Log.Error("External signup with unknown ProviderId");
                    return(Problem(_localizer[DataTransferer.ExternalAuthenticationWithUnknownProvider().Message]));
                }

                externalUser.DeviceId   = headerbindingmodel.DeviceId;
                externalUser.DeviceName = headerbindingmodel.DeviceName;
                externalUser.DeviceType = headerbindingmodel.DeviceType;

                var accountprofile = await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema {
                    TypeId   = AccountProfileType.Email.ToInt(),
                    LinkedId = externalUser.Email
                }).ConfigureAwait(true);

                if (accountprofile == null)
                {
                    Log.Debug($"User {User.Identity.Name} try to sign in for first time at {DateTime.UtcNow}");
                    return(Ok(_accountService.ExternalSignupAsync(externalUser)));
                }
                else
                {
                    Log.Debug($"Account with Id={accountprofile.AccountId} try to sign in at {DateTime.UtcNow}");
                    var result = await _accountService.ExternalSigninAsync(externalUser, accountprofile).ConfigureAwait(false);

                    switch (result.Code)
                    {
                    case 200:
                        return(Ok(result.Data));

                    case 500:
                        return(Problem(_localizer[result.Message]));

                    default:
                        return(BadRequest(_localizer[result.Message]));
                    }
                }
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }
Пример #10
0
        public async Task <IActionResult> ChangeForgotenPasswordAsync([FromBody] ChangeForgotenPasswordBindingModel collection)
        {
            Log.Debug($"ChangeForgotenPassword => {JsonConvert.SerializeObject(collection)}");

            try {
                if (string.IsNullOrEmpty(collection?.Username))
                {
                    return(BadRequest(_localizer[DataTransferer.DefectiveEmailOrCellPhone().Message]));
                }
                collection.Username = collection.Username.Trim();

                if (string.IsNullOrEmpty(collection.NewPassword) && string.IsNullOrEmpty(collection.ConfirmPassword))
                {
                    return(BadRequest(_localizer[DataTransferer.DefectivePassword().Message]));
                }

                if (collection.NewPassword != collection.ConfirmPassword)
                {
                    return(BadRequest(_localizer[DataTransferer.PasswordsMissmatch().Message]));
                }

                if (string.IsNullOrWhiteSpace(collection.Token))
                {
                    return(BadRequest(_localizer[DataTransferer.UnofficialRequest().Message]));
                }

                var query = new AccountProfileGetFirstSchema {
                    LinkedId = collection.Username
                };
                if (collection.Username.IsPhoneNumber())
                {
                    query.TypeId = AccountProfileType.Phone.ToInt();
                }
                else if (new EmailAddressAttribute().IsValid(collection.Username))
                {
                    query.TypeId = AccountProfileType.Email.ToInt();
                }
                else
                {
                    return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
                }

                var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true);

                if (accountProfile == null)
                {
                    if (query.TypeId == AccountProfileType.Phone.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.PhoneNotFound().Message]));
                    }

                    if (query.TypeId == AccountProfileType.Email.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailNotFound().Message]));
                    }
                }

                var cachedToken = _memoryCache.Get(collection.Username);
                if (cachedToken == null)
                {
                    return(BadRequest(_localizer[DataTransferer.ChangingPasswordWithoutToken().Message]));
                }

                var account = await _accountService.FirstAsync(new AccountGetFirstSchema {
                    Id = accountProfile.AccountId.Value
                }).ConfigureAwait(true);

                if (account == null)
                {
                    return(BadRequest(_localizer[DataTransferer.UserNotFound().Message]));
                }

                if (collection.Token != cachedToken.ToString())
                {
                    Log.Warning($"Account => {account}, AccountProfile => {accountProfile}, It tried to change its password with a wrong 'ForgotPasswordToken'");
                    return(BadRequest(_localizer[DataTransferer.ChangingPasswordWithWrongToken().Message]));
                }

                _memoryCache.Remove(collection.Username);

                await _accountService.UpdateAsync(new AccountUpdateSchema {
                    Id       = account.Id.Value,
                    Password = _cryptograph.RNG(collection.NewPassword)
                }).ConfigureAwait(false);

                return(Ok(_localizer[DataTransferer.PasswordChanged().Message]));
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }
Пример #11
0
        public async Task <IActionResult> ForgotPasswordAsync([FromBody] ForgotPasswordBindingModel collection)
        {
            Log.Debug($"ForgotPassword => {JsonConvert.SerializeObject(collection)}");

            if (string.IsNullOrEmpty(collection?.Username))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEmailOrCellPhone().Message]));
            }
            collection.Username = collection.Username.Trim();

            try {
                var query = new AccountProfileGetFirstSchema {
                    LinkedId = collection.Username
                };
                if (collection.Username.IsPhoneNumber())
                {
                    query.TypeId = AccountProfileType.Phone.ToInt();
                }
                else if (new EmailAddressAttribute().IsValid(collection.Username))
                {
                    query.TypeId = AccountProfileType.Email.ToInt();
                }
                else
                {
                    return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
                }

                var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true);

                if (accountProfile == null)
                {
                    if (query.TypeId == AccountProfileType.Phone.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.PhoneNotFound().Message]));
                    }

                    if (query.TypeId == AccountProfileType.Email.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailNotFound().Message]));
                    }
                }

                var token         = _randomMaker.NewToken();
                var username      = Convert.ToBase64String(Encoding.UTF8.GetBytes(collection.Username));
                var changepassurl = $"clipboardy.com/api/account/changepasswordrequested?username={username}&token={token}";
                _memoryCache.Set(username, token, DateTime.Now.AddMinutes(10));

                if (query.TypeId == AccountProfileType.Phone.ToInt())
                {
                    await _smsService.SendAsync(new SMSModel {
                        PhoneNo  = accountProfile.LinkedId,
                        TextBody = $"{DataTransferer.ForgotPasswordSMSBody().Message} \r\n {changepassurl}"
                    }).ConfigureAwait(false);
                }
                else
                {
                    await _emailService.SendAsync(new EmailModel {
                        Address    = accountProfile.LinkedId,
                        Subject    = _localizer[DataTransferer.ForgotPasswordEmailSubject().Message],
                        IsBodyHtml = true,
                        Body       = $"<p>{DataTransferer.ForgotPasswordEmailBody().Message}</p>" +
                                     $"<p>{changepassurl}</p>"
                    }).ConfigureAwait(false);
                }

                return(Ok(changepassurl));
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }
 private void Awake()
 {
     instance = this;
 }
Пример #13
0
        public async Task <ActionResult> ActivationRequestAsync()
        {
            var query = new AccountProfileGetFirstSchema {
                LinkedId = CurrentAccount.Username
            };

            if (CurrentAccount.Username.IsPhoneNumber())
            {
                query.TypeId = AccountProfileType.Phone.ToInt();
            }
            else if (new EmailAddressAttribute().IsValid(CurrentAccount.Username))
            {
                query.TypeId = AccountProfileType.Email.ToInt();
            }
            else
            {
                return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
            }

            try {
                var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true);

                if (accountProfile == null)
                {
                    if (query.TypeId == AccountProfileType.Phone.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.PhoneNotFound().Message]));
                    }

                    if (query.TypeId == AccountProfileType.Email.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailNotFound().Message]));
                    }
                }

                var activationCode = _randomMaker.NewNumber(10000, 99999);
                _memoryCache.Set(CurrentAccount.Username, activationCode, DateTime.Now.AddMinutes(10));

                if (query.TypeId == AccountProfileType.Phone.ToInt())
                {
                    await _smsService.SendAsync(new SMSModel {
                        PhoneNo  = accountProfile.LinkedId,
                        TextBody = $"{DataTransferer.ActivationCodeSMSBody().Message} \r\n {activationCode}"
                    }).ConfigureAwait(false);
                }
                else
                {
                    await _emailService.SendAsync(new EmailModel {
                        Address    = accountProfile.LinkedId,
                        Subject    = _localizer[DataTransferer.ActivationCodeEmailSubject().Message],
                        IsBodyHtml = true,
                        Body       = $"<p>{DataTransferer.ActivationCodeEmailBody().Message}</p>" +
                                     $"<p>{activationCode}</p>"
                    }).ConfigureAwait(false);
                }

                return(Ok(_localizer[DataTransferer.ActivationCodeRequested().Message]));
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem());
            }
        }
Пример #14
0
        public async Task <IServiceResult> ExternalSigninAsync(ExternalUserBindingModel externalUser, AccountProfileResult accountProfile)
        {
            if (accountProfile == null && accountProfile.AccountId.HasValue)
            {
                return(DataTransferer.DefectiveEntry());
            }

            if (accountProfile.StatusId != Status.Active)
            {
                return(DataTransferer.UserIsNotActive());
            }

            var now = DateTime.UtcNow;

            var accountQuery = new AccountGetFirstSchema {
                Id       = accountProfile.AccountId,
                StatusId = Status.Active.ToInt()
            };
            var account = await FirstAsync(accountQuery);

            if (account == null)
            {
                return(DataTransferer.UserNotFound());
            }

            // todo: check the account
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try {
                    var accountDeviceQuery = new AccountDeviceGetFirstSchema {
                        AccountId = account.Id,
                        DeviceId  = externalUser.DeviceId
                    };
                    var accountDevice = await _accountDeviceService.FirstAsync(accountDeviceQuery);

                    if (accountDevice == null)
                    {
                        return(DataTransferer.DeviceIdNotFound());
                    }

                    int deviceId;
                    if (accountDevice != null)
                    {
                        deviceId = accountDevice.Id.Value;
                        // set a new token
                        await _accountDeviceService.UpdateAsync(new AccountDeviceUpdateSchema {
                            Id = accountDevice.Id.Value
                        });
                    }
                    else
                    {
                        // create new device for account
                        deviceId = await _accountDeviceService.AddAsync(new AccountDeviceAddSchema {
                            AccountId  = account.Id,
                            DeviceId   = externalUser.DeviceId,
                            DeviceName = externalUser.DeviceName,
                            DeviceType = externalUser.DeviceType,
                            CreatedAt  = now,
                            StatusId   = Status.Active.ToInt()
                        });
                    }

                    // clean forgot password tokens
                    //account.Id.Value, transaction
                    await _accountProfileService.CleanForgotPasswordTokensAsync(account.Id.Value);

                    //if(accountProfileCleanTokens.StatusCode != 200) {
                    //    Log.Error($"Can't update 'ForgotPasswordTokens' to NULL for AccountId={account.Id}");
                    //    return DataTransferer.SomethingWentWrong();
                    //}

                    // set last signed in at
                    var accountUpdate = new AccountUpdateSchema {
                        Id             = account.Id.Value,
                        LastSignedinAt = now
                    };
                    await UpdateAsync(accountUpdate);

                    if (accountUpdate.StatusCode != 200)
                    {
                        Log.Error($"Can't update 'LastSignedinAt' after a successfully signing in for AccountId={account.Id}");
                    }

                    transaction.Complete();
                    var token = _jwtHandler.Bearer(new Account(account.Id.Value, deviceId, account.Username, now).ToClaimsIdentity());
                    return(DataTransferer.Ok(token));
                }
                catch (Exception ex) {
                    Log.Error(ex, ex.Source);
                    return(DataTransferer.InternalServerError(ex));
                }
            }
        }
Пример #15
0
        public async Task <IServiceResult> SigninAsync(SigninBindingModel signinModel)
        {
            var now = DateTime.UtcNow;

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try {
                    var query = new AccountProfileGetFirstSchema {
                        LinkedId = signinModel.Username
                                   //StatusId = Status.Active
                    };
                    if (signinModel.Username.IsPhoneNumber())
                    {
                        query.TypeId = AccountProfileType.Phone.ToInt();
                    }
                    else if (new EmailAddressAttribute().IsValid(signinModel.Username))
                    {
                        query.TypeId = AccountProfileType.Email.ToInt();
                    }
                    else
                    {
                        return(DataTransferer.InvalidEmailOrCellPhone());
                    }

                    var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true);

                    if (accountProfile == null)
                    {
                        if (query.TypeId == AccountProfileType.Phone.ToInt())
                        {
                            return(DataTransferer.PhoneNotFound());
                        }
                        else
                        {
                            return(DataTransferer.EmailNotFound());
                        }
                    }

                    var account = await FirstAsync(new AccountGetFirstSchema {
                        Id       = accountProfile.AccountId,
                        StatusId = Status.Active.ToInt()
                    }).ConfigureAwait(true);

                    if (account == null)
                    {
                        return(DataTransferer.UserIsNotActive());
                    }

                    var deviceId = 0;
                    // check password
                    if (_cryptograph.IsEqual(signinModel.Password, account.Password))
                    {
                        var accountDeviceQuery = new AccountDeviceGetFirstSchema {
                            AccountId = account.Id,
                            DeviceId  = signinModel.DeviceId
                        };
                        var accountDevice = await _accountDeviceService.FirstAsync(accountDeviceQuery);

                        // todo: check the accountDevice

                        if (accountDevice != null)
                        {
                            deviceId = accountDevice.Id.Value;
                            // set new token
                            await _accountDeviceService.UpdateAsync(new AccountDeviceUpdateSchema {
                                Id = accountDevice.Id.Value,
                            });
                        }
                        else
                        {
                            // create new device for account
                            deviceId = await _accountDeviceService.AddAsync(new AccountDeviceAddSchema {
                                AccountId  = account.Id,
                                DeviceId   = signinModel.DeviceId,
                                DeviceName = signinModel.DeviceName,
                                DeviceType = signinModel.DeviceType,
                                CreatedAt  = now,
                                StatusId   = Status.Active.ToInt()
                            });
                        }
                    }
                    else
                    {
                        return(DataTransferer.WrongPassword());
                    }

                    // clean forgot password tokens
                    await _accountProfileService.CleanForgotPasswordTokensAsync(account.Id.Value);

                    //if(accountProfilesQuery.StatusCode != 200) {
                    //    Log.Error($"Can't update 'ForgotPasswordTokens' to NULL for AccountId={account.Id}");
                    //    return DataTransferer.SomethingWentWrong();
                    //}

                    // set last signed in at
                    var changedAccount = UpdateAsync(new AccountUpdateSchema {
                        LastSignedinAt = now
                    });

                    transaction.Complete();
                    var token = _jwtHandler.Bearer(new Account(account.Id.Value, deviceId, signinModel.Username, now).ToClaimsIdentity());
                    return(DataTransferer.Ok(token));
                }
                catch (Exception ex) {
                    Log.Error(ex, ex.Source);
                    return(DataTransferer.InternalServerError());
                }
            }
        }
Пример #16
0
        public async Task <ActionResult> ActivateAccountAsync([FromBody] ActivateAccountBindingModel collection)
        {
            if (collection == null ||
                string.IsNullOrWhiteSpace(collection.Username) ||
                string.IsNullOrWhiteSpace(collection.Code))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
            }

            var query = new AccountProfileGetFirstSchema {
                LinkedId = collection.Username
            };

            if (collection.Username.IsPhoneNumber())
            {
                query.TypeId = AccountProfileType.Phone.ToInt();
            }
            else if (new EmailAddressAttribute().IsValid(collection.Username))
            {
                query.TypeId = AccountProfileType.Email.ToInt();
            }
            else
            {
                return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
            }

            try {
                var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true);

                if (accountProfile == null)
                {
                    if (query.TypeId == AccountProfileType.Phone.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.PhoneNotFound().Message]));
                    }

                    if (query.TypeId == AccountProfileType.Email.ToInt())
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailNotFound().Message]));
                    }
                }

                var activationCode = _memoryCache.Get(collection.Username);
                if (activationCode == null)
                {
                    return(BadRequest(_localizer[DataTransferer.ActivationCodeRequestedNotFound().Message]));
                }

                if (collection.Code != activationCode.ToString())
                {
                    return(BadRequest(_localizer[DataTransferer.ActivationCodeRequestedNotFound().Message]));
                }

                _memoryCache.Remove(collection.Username);
                var accountProfileQuery = new AccountProfileUpdateSchema {
                    Id       = accountProfile.Id.Value,
                    StatusId = Status.Active.ToInt()
                };
                await _accountProfileService.UpdateAsync(accountProfileQuery).ConfigureAwait(true);

                return(Ok(_localizer[DataTransferer.AccountActivated().Message]));
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem());
            }
        }
Пример #17
0
        public async Task <IActionResult> SignupAsync([FromBody] SignupBindingModel collection)
        {
            // todo: Captcha

            if (collection == null)
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
            }

            if (string.IsNullOrEmpty(collection?.Username))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEmailOrCellPhone().Message]));
            }

            Log.Debug($"A User is trying to register with this data: {JsonConvert.SerializeObject(collection)}");
            collection.Username = collection.Username.Trim();

            try {
                if (collection.Username.IsPhoneNumber())
                {
                    collection.Phone = collection.Username;
                    if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema {
                        LinkedId = collection.Phone
                    }).ConfigureAwait(true) != null)
                    {
                        return(BadRequest(_localizer[DataTransferer.CellPhoneAlreadyExists().Message]));
                    }
                }
                else if (new EmailAddressAttribute().IsValid(collection.Username))
                {
                    collection.Email = collection.Username;
                    if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema {
                        LinkedId = collection.Email
                    }).ConfigureAwait(true) != null)
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailAlreadyExists().Message]));
                    }
                }
                else
                {
                    return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
                }

                if (string.IsNullOrEmpty(collection.Password) && string.IsNullOrEmpty(collection.ConfirmPassword))
                {
                    return(BadRequest(_localizer[DataTransferer.DefectivePassword().Message]));
                }

                if (collection.Password != collection.ConfirmPassword)
                {
                    return(BadRequest(_localizer[DataTransferer.PasswordsMissmatch().Message]));
                }

                if (string.IsNullOrEmpty(collection.DeviceId) || string.IsNullOrEmpty(collection.DeviceName))
                {
                    return(BadRequest(_localizer[DataTransferer.UnofficialRequest().Message]));
                }

                var result = await _accountService.SignupAsync(collection).ConfigureAwait(true);

                switch (result.Code)
                {
                case 200:
                    return(Ok(result.Data));

                case 400:
                    return(BadRequest(result.Message));

                case 500:
                default:
                    return(Problem(result.Message));
                }
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }