Exemplo n.º 1
0
        public async Task <IActionResult> Post(
            [FromBody] AuthLoginBinding binding,
            [FromServices] UserSecurityService gamerSecurityService,
            CancellationToken cancellationToken)
        {
            var gamer = await _authorizationRepository.GetUser(binding.Login, cancellationToken);

            if (gamer == null)
            {
                throw new ApiException(HttpStatusCode.NotFound, ErrorCodes.Forbidden, "");
            }

            if (String.IsNullOrEmpty(gamer.Password))
            {
                gamerSecurityService.CreatePassword(gamer, binding.Password);
                await _authorizationRepository.SaveUser(gamer);
            }
            else
            {
                if (!gamerSecurityService.TestPassword(gamer, binding.Password))
                {
                    throw new ApiException(HttpStatusCode.Unauthorized, ErrorCodes.Forbidden, "");
                }
            }

            var sessionId = Guid.NewGuid();

            await _authorizationRepository.SaveSession(new Session(sessionId, gamer.Id, 60 * 26, HttpContext.GetIp()));

            var roles = new List <String>();

            if (gamer.Roles != null)
            {
                roles.AddRange(gamer.Roles);
            }
            roles.Add(gamer.Rank.ToString().ToLower());
            return(Ok(new TokenView
            {
                Token = sessionId,
                GuildId = gamer.GuildId,
                Roles = roles.Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray()
            }));
        }
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context.HttpContext.Request.Method.Equals(HttpMethod.Options.Method))
            {
                return;
            }

            var userId = context.HttpContext.GetUserId();

            var gamer = await _authorizationRepository.GetUser(userId, CancellationToken.None);

            if (!_roles.Any())
            {
                return;
            }

            if (gamer.Roles != null)
            {
                if (_roles.Any(role => gamer.Roles.Contains(role)))
                {
                    return;
                }
            }

            if (_roles.Any(role => gamer.Rank.ToString().Equals(role, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            context.Result = new ObjectResult(new ProblemDetails
            {
                Type   = ErrorCodes.Forbidden,
                Detail = "access denied",
                Status = (Int32)HttpStatusCode.Forbidden,
            })
            {
                StatusCode = (Int32)HttpStatusCode.Forbidden
            };
        }