Ejemplo n.º 1
0
        public async Task <IActionResult> GetMe()
        {
            // Grab the UserId from | User ->> part of ControllerBase
            var userId = UserId;

            // If there is no userId
            if (string.IsNullOrEmpty(userId))
            {
                return(BadRequest());
            }

            // Grab the User => compare User Id with userId that's coming from User Claim -> "sub"
            var user = await _ctx.Users
                       .Where(x => x.Id.Equals(userId))
                       .Include(x => x.Submissions)
                       .ThenInclude(x => x.Votes)
                       .Select(UserViewModel.ProfileProjection(IsMod))
                       .FirstOrDefaultAsync();

            // If user is not equal to null -> return the User
            if (user != null)
            {
                return(Ok(user));
            }

            // If User is null -> Instantiate new User
            var newUser = new User
            {
                // Grab the userId and set it to Id
                Id = userId,

                // Grab the PreferredUserName claim type -> value from JWT, this claim should be contained in access_token
                Username = PreferredUsername
            };

            // Add the User to ctx
            _ctx.Add(newUser);

            // Save User to DB
            await _ctx.SaveChangesAsync();

            // Return User
            return(Ok(UserViewModel.CreateProfile(newUser, IsMod)));
        }