示例#1
0
        public Stocker getLogin(long cedula, string contrasena)
        {
            var     token      = "";
            Stocker sto        = null;
            Usuario _unusuario = FabricaLogica.getLUsuario().iniciarsesion(cedula, contrasena);

            if (_unusuario is Stocker)
            {
                sto = (Stocker)_unusuario;
                if (sto == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                token = TokenGenerator.GenerateTokenJwt(cedula.ToString());
            }

            return(sto);
        }
        public Administrador getLogin(long cedula, string contrasena)
        {
            var           token      = "";
            Administrador adminc     = null;
            Usuario       _unusuario = FabricaLogica.getLUsuario().iniciarsesion(cedula, contrasena);

            if (_unusuario is Administrador)
            {
                adminc = (Administrador)_unusuario;
                if (adminc == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                token = TokenGenerator.GenerateTokenJwt(cedula.ToString());
            }

            return(adminc);
        }
        public Cadete getLogin(long cedula, string contrasena)
        {
            var     token      = "";
            Cadete  cad        = null;
            Usuario _unusuario = FabricaLogica.getLUsuario().iniciarsesion(cedula, contrasena);

            if (_unusuario is Cadete)
            {
                cad = (Cadete)_unusuario;
                if (cad == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                token = TokenGenerator.GenerateTokenJwt(cedula.ToString());
            }

            return(cad);
        }
        public IHttpActionResult Authenticate(LoginRequest login)
        {
            //https://enmilocalfunciona.io/construyendo-una-web-api-rest-segura-con-json-web-token-en-net-parte-ii/
            if (login == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            int val = _usuarioController.iniciarSesion(login.Username, login.Password);

            if (val != 0)
            {
                //var currUsr =_usuarioController.GetUsuarioById(val);
                var token = TokenGenerator.GenerateTokenJwt(login.Username);
                return(Ok(token));
            }
            else
            {
                return(Unauthorized());
            }
            //MessageBox.Show("Usuario o clave incorrecto. \r\nVerifique por favor.");
        }
        public IActionResult Auth([FromBody] AuthRequest request)
        {
            try
            {
                var user = _service.Authenticate(request.Login, request.Password);

                string token = TokenGenerator.GenerateToken(_jwtSettings.Secret, user.Id.ToString());

                return(Ok(new AuthResponse
                {
                    Token = token
                }));
            }
            catch (InvalidParamsError)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, new
                {
                    message = "Логин и пароль обязательны для ввода"
                }));
            }
            catch (UserNotExistError)
            {
                return(StatusCode(StatusCodes.Status404NotFound, new
                {
                    message = "Пользователь не найден"
                }));
            }
            catch (VerifyPasswordError)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, new
                {
                    message = "Неверный пароль"
                }));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new { message = e.Message }));
            }
        }
示例#6
0
        public IHttpActionResult Login(Usuario _user)
        {
            if (_user == null || _user.Login.Trim().Length == 0 || _user.Password.Trim().Length == 0)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            try
            {
                //Nos logamos en el AD
                DirectoryEntry entry = new DirectoryEntry(ConfigHelper.AD_URL_ACTIVE_DIRECTORY)
                {
                    Username = _user.Login,
                    Password = _user.Password
                };

                //Filtramos los datos del usuario
                DirectorySearcher ds = new DirectorySearcher(entry)
                {
                    SearchScope = SearchScope.Subtree,
                    Filter      = "(&(objectClass=User) (samAccountName=" + _user.Login + "))"
                };

                //Cargamos las propiedades que necesitamos
                ds.PropertiesToLoad.Add("objectguid");
                ds.PropertiesToLoad.Add("sn");
                ds.PropertiesToLoad.Add("givenName");
                ds.PropertiesToLoad.Add("mail");

                SearchResult result = ds.FindOne();

                //Creamos el Token
                var token = TokenGenerator.GenerateTokenJwt(_user.Login);

                //Creamos el objeto del usuario
                _user.Id        = BitConverter.ToString((byte[])result.Properties["objectguid"][0]).Replace("-", string.Empty);
                _user.Token     = token;
                _user.Nombre    = result.Properties["givenName"][0].ToString();
                _user.Apellidos = result.Properties["sn"][0].ToString();
                _user.Password  = string.Empty;
                _user.Email     = result.Properties["mail"][0].ToString();
                _user.Groups    = new List <UsuarioGrupos>();

                //Recuperamos los grupos a los que pertenece el usuario
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
                {
                    // find a user
                    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, _user.Login);

                    if (user != null)
                    {
                        // get the user's groups
                        var groups = user.GetAuthorizationGroups();

                        foreach (GroupPrincipal group in groups)
                        {
                            _user.Groups.Add(new UsuarioGrupos()
                            {
                                Id     = group.Guid.ToString(),
                                Nombre = group.Name
                            });
                        }
                    }
                }

                return(Ok(_user));
            }
            catch (DirectoryServicesCOMException cex)
            {
                return(Unauthorized());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }