Ejemplo n.º 1
0
    public async Task <IActionResult> SignInByGoogle([FromBody] GoogleAuthRequest authRequest,
                                                     CancellationToken cancellationToken)
    {
        var googleUser = await _mediator.Send(new GetGoogleUser(authRequest.IdToken), cancellationToken);

        var token = await _mediator.Send(new ExternalAuth(googleUser.Email), cancellationToken);

        _cookieFactory.SetResponseRefreshTokenCookie(this, token.RefreshToken);

        return(Ok(token));
    }
        public async Task <IActionResult> GoogleAuth([FromBody] GoogleAuthRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new AuthFailedResponse
                {
                    Errors = ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage))
                }));
            }
            var authResponse = await _delivermanService.GoogleLoginDeliverymanAsync(request);

            if (!authResponse.Success)
            {
                return(BadRequest(new AuthFailedResponse {
                    Errors = authResponse.Errors
                }));
            }
            return(Ok(new AuthSuccessResponse {
                Token = authResponse.Token
            }));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Google(GoogleAuthRequest authRequest)
        {
            var userId = authRequest.UserId;

            return(Redirect($"/setup/{userId}"));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> GoogleAutentificar([FromBody] GoogleAuthRequest googleAuthRequest)
        {
            AuthRequest  authRequest  = new();
            AuthResponse authResponse = new();

            try
            {
                //The authentication API will use the idToken from google and verify it.
                GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();

                //Here goes the app google client ID
                settings.Audience = new List <string>()
                {
                    "225689514544-qccdbtr164tekpjkgq0fn1f7630g2266.apps.googleusercontent.com"
                };

                GoogleJsonWebSignature.Payload payload = GoogleJsonWebSignature.ValidateAsync(googleAuthRequest.Id_token, settings).Result;


                //***LOGIN***
                //Revisa si el usuario figura en los registros de la base de datos, si es asi lo logea
                string hashCommonPassword = Encrypt.GetSHA256(_CommonPassSettings.Pass);
                bool   existe             = _context.Usuarios.Any(u => u.NombreUsuario == payload.Email && u.Clave == hashCommonPassword && u.Disabled.Equals(false));

                if (existe)
                {
                    //Then it creates an access token that grants access to the other APIs of your app.
                    authRequest.NombreUsuario = payload.Email;
                    authRequest.Clave         = _CommonPassSettings.Pass;

                    authResponse = await _authService.Authorize(authRequest);

                    return(Ok(authResponse));
                }


                //***REGISTRER...***
                //Agregamos el usuario nuevo
                Usuario usuarioNuevo = new();
                usuarioNuevo.NombreUsuario = payload.Email;
                usuarioNuevo.Clave         = hashCommonPassword;
                usuarioNuevo.RolID         = 1; //Corresponde al Cliente en la base de datos de Roles
                _context.Usuarios.Add(usuarioNuevo);
                _context.SaveChanges();         //Debería hacerse de forma asincrona, cambiar eso

                //Luego agregamos el cliente nuevo
                Cliente clienteNuevo = new();
                clienteNuevo.Nombre    = payload.GivenName;
                clienteNuevo.Apellido  = payload.FamilyName;
                clienteNuevo.Telefono  = 0;
                clienteNuevo.UsuarioID = usuarioNuevo.Id;
                _context.Clientes.Add(clienteNuevo);
                _context.SaveChanges(); //Debería hacerse de forma asincrona, cambiar eso

                //***...then LOGIN***
                //Then it creates an access token that grants access to the other APIs of your app.
                authRequest.NombreUsuario = payload.Email;
                authRequest.Clave         = _CommonPassSettings.Pass;

                authResponse = await _authService.Authorize(authRequest);

                return(Ok(authResponse));
            }
            catch
            {
                Console.WriteLine("Error en GoogleAuth");
            }
            return(StatusCode(500));
        }
Ejemplo n.º 5
0
        public async Task <AuthenticationResponse> GoogleLoginStoreOwnerAsync(GoogleAuthRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.FirstName) || string.IsNullOrWhiteSpace(request.LastName) || string.IsNullOrWhiteSpace(request.Email))
            {
                return new AuthenticationResponse {
                           Errors = new[] { "FirstName, LastName and Email cannot be empty." }
                }
            }
            ;
            var storeOwnerExist = await _dataContext.StoreOwners.FirstOrDefaultAsync(s => s.EmailAddress == request.Email);

            if (storeOwnerExist != null) // Sign Store Owner in
            {
                storeOwnerExist.LastLoginDate = DateTime.Now;

                _dataContext.Entry(storeOwnerExist).State = EntityState.Modified;
                var updated = await _dataContext.SaveChangesAsync();

                if (updated <= 0)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to signin." }
                    }
                }
                ;

                var token = GenerateAuthenticationTokenForStoreOwner(storeOwnerExist);
                return(new AuthenticationResponse {
                    Success = true, Token = token
                });
            }
            else // Register Store Owner
            {
                var newStoreOwner = new StoreOwner()
                {
                    EmailAddress       = request.Email,
                    FirstName          = request.FirstName,
                    MiddleName         = request.MiddleName,
                    LastName           = request.LastName,
                    PhoneNumber        = request.PhoneNumber,
                    ProfilePicUrl      = request.ImageUrl,
                    IsVerified         = true,
                    DateRegistered     = DateTime.Now,
                    IsGoogleRegistered = true
                };
                await _dataContext.StoreOwners.AddAsync(newStoreOwner);

                var created = await _dataContext.SaveChangesAsync();

                if (created <= 0)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to register customer." }
                    }
                }
                ;

                var token = GenerateAuthenticationTokenForStoreOwner(newStoreOwner);
                return(new AuthenticationResponse {
                    Success = true, Token = token
                });
            }
        }