Exemplo n.º 1
0
        public IActionResult Login([FromBody] LoginData login)
        {
            if (login?.Email == null || login?.Password == null)
            {
                return(BadRequest("Password and/or email is missing."));
            }

            logger.LogInformation("login request {0}", login.Email);

            var authConfiguration = configuration.GetSection("AuthDbConnection");

            // TODO DI
            var repo = new AuthRepo(
                authConfiguration.GetValue <string>("ConnectionString"),
                authConfiguration.GetValue <string>("DbName"),
                authConfiguration.GetValue <string>("CollectionName"));

            var auth         = repo.GetAuthentication(login.Email);
            var passwordHash = login.Password.ToSHA256Hash();

            if (auth == null ||
                auth.Password?.Equals(passwordHash, StringComparison.InvariantCulture) == false ||
                auth.Email?.Equals(login.Email, StringComparison.InvariantCultureIgnoreCase) == false)
            {
                logger.LogInformation("login failed {0}", login.Email);
                return(Unauthorized());
            }

            var keyparts = configuration.GetSection("Secrets:RSA-PrivateKey").GetChildren().Select(c => c.Value);

            var privateKey     = string.Join(Environment.NewLine, keyparts);
            var jwtHelpert     = new JwtHelper(privateKey);
            var payload        = jwtHelpert.CreatePayload(auth);
            var jwtBearerToken = payload.CreateToken();

            // uncomment if you want to return the token as http only cookie
            // HttpContext.Response.Cookies.Append("SESSIONID", jwtBearerToken, new CookieOptions() { HttpOnly = true, Secure = true });
            logger.LogInformation("login success {0}", login.Email);
            return(Created("", new {
                token = jwtBearerToken,
                // additional data so that client does not need to decode those from the token
                payload.expiresAt,
                userId = auth.UserId
            }));
        }