Exemplo n.º 1
0
        public IActionResult UploadImagesToPost(int id, [FromForm] IFormFileCollection images, IFormFile mainImage)
        {
            try
            {
                int?uId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (uId == null)
                {
                    return(Unauthorized(new ErrorExceptionModel("Sem Autorização ou sem sessão inciada")));
                }
                PublicationDAO pDAO = new PublicationDAO(_connection);
                Publication    p    = pDAO.FindById(id);
                if (p.UtilizadorId != uId)
                {
                    return(NotFound("Publicação não encontrada!"));
                }

                bool result = pDAO.UploadImagesToPost(id, images, mainImage);

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        protected void Session_Start(object sender, EventArgs e)
        {
            // Note that the application does not go to the database
            // to authenticate the user.
            // The authentication is done by the issuer.
            // WSFederationAuthenticationModule automatically reads the
            // user token sent by the IP and sets the user information
            // in the thread current principal.
            if (this.Context.User.Identity.IsAuthenticated)
            {
                // At this point we can access the authenticated user information
                // by accessing the property Thread.CurrentPrincipal.
                string issuer = ClaimHelper.GetCurrentUserClaim(ClaimTypes.Name).OriginalIssuer;

                // Note, the GetClaim extension method is defined in the Samples.Web.Utillities project
                string givenName  = ClaimHelper.GetCurrentUserClaim(WSIdentityConstants.ClaimTypes.GivenName).Value;
                string surname    = ClaimHelper.GetCurrentUserClaim(WSIdentityConstants.ClaimTypes.Surname).Value;
                string costCenter = ClaimHelper.GetCurrentUserClaim(Adatum.ClaimTypes.CostCenter).Value;

                var    repository        = new UserRepository();
                string federatedUsername = GetFederatedUserName(issuer, this.User.Identity.Name);
                var    user = repository.GetUser(federatedUsername);
                user.CostCenter = costCenter;
                user.FullName   = givenName + " " + surname;

                // The user is stored in the session because the application
                // authentication strategy requires it.
                this.Context.Session["LoggedUser"] = user;
            }
        }
Exemplo n.º 3
0
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                return;
            }

            if (filterContext.Controller.ViewData.Model == null)
            {
                filterContext.Controller.ViewData.Model = new MasterPageViewModel();
            }

            var model = (MasterPageViewModel)filterContext.Controller.ViewData.Model;

            var organizationName       = ClaimHelper.GetCurrentUserClaim(Fabrikam.ClaimTypes.Organization).Value;
            var organizationRepository = new OrganizationRepository();
            var tenantLogoPath         = organizationRepository.GetOrganization(organizationName).LogoPath;

            model.TenantLogoPath = tenantLogoPath;

            model.ClaimsIssuer =
                ClaimHelper.GetCurrentUserClaim(ClaimTypes.Name).
                Issuer;
            model.ClaimsOriginalIssuer =
                ClaimHelper.GetCurrentUserClaim(Fabrikam.ClaimTypes.IdentityProvider).Value;

            base.OnActionExecuted(filterContext);
        }
Exemplo n.º 4
0
        public IActionResult deleteImage(int post, ImageName image)
        {
            int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (id == null)
            {
                return(Unauthorized(new ErrorMessageModel("Sem Autorização ou sem sessão inciada")));
            }

            if (image == null)
            {
                return(BadRequest(new ErrorMessageModel("Nome de imagem não enviado!")));
            }

            try
            {
                JobDAO jobDAO  = new JobDAO(_connection, this._environment.ContentRootPath);
                bool   deleted = jobDAO.deleteImage((int)id, post, image);

                if (deleted == true)
                {
                    return(Ok(new SuccessMessageModel("Imagem apagada!")));
                }
                else
                {
                    return(BadRequest(new ErrorMessageModel("Imagem não apagada ou inexistente!")));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 5
0
        public async Task <ActionResult> About()
        {
            var myGroups         = new List <Group>();
            var myDirectoryRoles = new List <DirectoryRole>();

            try
            {
                ClaimsIdentity claimsId  = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
                List <string>  objectIds = await ClaimHelper.GetGroups(claimsId);

                await GraphHelper.GetDirectoryObjects(objectIds, myGroups, myDirectoryRoles);
            }
            catch (AdalException e)
            {
                // If the user doesn't have an access token, they need to re-authorize
                if (e.ErrorCode == "failed_to_acquire_token_silently")
                {
                    return(RedirectToAction("Reauth", "Error", new { redirectUri = Request.Url }));
                }

                return(RedirectToAction("ShowError", "Error", new { errorMessage = "Error while acquiring token." }));
            }
            catch (Exception e)
            {
                return(RedirectToAction("ShowError", "Error", new { errorMessage = e.Message }));
            }

            ViewData["myGroups"]         = myGroups;
            ViewData["myDirectoryRoles"] = myDirectoryRoles;
            ViewData["overageOccurred"]  = (ClaimsPrincipal.Current.FindFirst("_claim_names") != null &&
                                            (System.Web.Helpers.Json.Decode(ClaimsPrincipal.Current.FindFirst("_claim_names").Value)).groups != null);
            return(View());
        }
        public ActionResult Index()
        {
            var repository = new ShipmentRepository();

            // users in Shipment Manager role can see all the shipments,
            // while others can see only its own shipments
            IEnumerable <Shipment> shipments;
            var organization = ClaimHelper.GetCurrentUserClaim(Fabrikam.ClaimTypes.Organization).Value;

            if (this.User.IsInRole(Fabrikam.Roles.ShipmentManager))
            {
                shipments = repository.GetShipmentsByOrganization(organization);
            }
            else
            {
                var userName = this.User.Identity.Name;
                shipments = repository.GetShipmentsByOrganizationAndUserName(organization, userName);
            }

            var model = new ShipmentListViewModel
            {
                Shipments = shipments
            };

            return(View(model));
        }
Exemplo n.º 7
0
        public ActionResult <List <FavoriteModel> > FavoritesList()
        {
            try
            {
                int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (id == null)
                {
                    return(Unauthorized(new ErrorMessageModel("Sem Autorização ou sem sessão inciada")));
                }

                EmployerDAO employerDAO = new EmployerDAO(_connection);

                List <FavoriteModel> favorites = employerDAO.FavoritesList((int)id).ToList();

                if (favorites == null)
                {
                    return(NotFound(new ErrorMessageModel("Lista de favoritos Inexistente!")));
                }

                return(favorites);
            }
            catch (Exception ex)
            {
                return(BadRequest(new ErrorMessageModel(ex.Message)));
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Add  general claims
 /// </summary>
 public void AddClaimsToIdentity(string role, string name, string userId,
                                 TimeSpan userTimeZoneOffset, ClaimsIdentity identity)
 {
     ClaimHelper.AddClaim(new Claim(ClaimTypes.Role, role), identity);                                           // role claim
     ClaimHelper.AddClaim(new Claim(ClaimTypes.Name, name), identity);                                           // user name claim
     ClaimHelper.AddClaim(new Claim(ISTUserClaims.UserTimeZoneOffset, userTimeZoneOffset.ToString()), identity); // User TimeZoneOffset claim
 }
Exemplo n.º 9
0
        public IActionResult deleteProfilePicture()
        {
            int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (id == null)
            {
                return(Unauthorized(new ErrorExceptionModel("Sem Autorização ou sem sessão inciada")));
            }
            try
            {
                UserDAO userDAO = new UserDAO(_connection);
                bool    deleted = userDAO.deleteImage((int)id);

                if (deleted == true)
                {
                    return(Ok(new SuccessExceptionModel("Imagem apagada!")));
                }
                else
                {
                    return(BadRequest(new ErrorExceptionModel("Imagem não apagada ou inexistente!")));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorExceptionModel(e.Message)));
            }
        }
Exemplo n.º 10
0
        public ActionResult <SuccessMessageModel> Reschedule(int id, DateModel date)
        {
            try{
                int?employerId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (employerId == null)
                {
                    return(Unauthorized(new ErrorMessageModel("Utilizador não existe!")));
                }

                WorkDAO          workDao = new WorkDAO(_connection);
                WorkDetailsModel work    = workDao.FindById(id, (int)employerId);

                if (work == null)
                {
                    return(BadRequest(new ErrorMessageModel("O trabalho não existe ou não está associado ao Employer!")));
                }

                bool updated = workDao.updateDate(id, date);

                if (updated)
                {
                    return(Ok(new SuccessMessageModel("Data atualizada com sucesso!")));
                }
                else
                {
                    return(BadRequest(new ErrorMessageModel("Erro! A data não foi atualizada!")));
                }
            } catch (Exception e) {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Add Domain License Detail Claims
        /// </summary>
        private void AddDomainLicenseDetailClaims(long domainKey, ClaimsIdentity identity)
        {
            DomainLicenseDetail domainLicenseDetail = null;

            //domainLicenseDetailsRepository.GetDomainLicenseDetailByDomainKey(domainKey);
            if (domainLicenseDetail != null)
            {
                var claim = new Claim(CaresUserClaims.DomainLicenseDetail,
                                      ClaimHelper.Serialize(
                                          new DomainLicenseDetailClaim
                {
                    UserDomainKey = domainLicenseDetail.UserDomainKey,
                    Branches      = domainLicenseDetail.Branches,
                    FleetPools    = domainLicenseDetail.FleetPools,
                    Employee      = domainLicenseDetail.Employee,
                    RaPerMonth    = domainLicenseDetail.RaPerMonth,
                    Vehicles      = domainLicenseDetail.Vehicles
                }),
                                      typeof(DomainLicenseDetailClaim).AssemblyQualifiedName);
                ClaimHelper.AddClaim(claim, identity);
            }
            else
            {
                throw new InvalidOperationException("No Domain License Detail data found!");
            }
        }
Exemplo n.º 12
0
        public IActionResult GetUserById(int userId)
        {
            int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (id == null)
            {
                return(Unauthorized(new ErrorMessageModel("Sem Autorização ou sem sessão inciada")));
            }

            try
            {
                UserDAO userDAO = new UserDAO(_connection, this._environment.ContentRootPath);
                User    user    = userDAO.FindById(userId);

                if (user == null)
                {
                    return(BadRequest(new ErrorMessageModel("Utilizador não encontrado!")));
                }

                return(Ok(user));
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Create(PuplicationCreate model)
        {
            int?uId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (uId == null)
            {
                return(Unauthorized(new ErrorExceptionModel("Sem Autorização ou sem sessão inciada")));
            }
            if (model.ImagePath == null)
            {
                model.ImagePath = 0;
            }
            model.UtilizadorId = (int)uId;

            PublicationDAO publicationDao    = new PublicationDAO(_connection);
            Publication    resultPublication = publicationDao.Create(model);

            resultPublication.UtilizadorId        = (int)uId;
            resultPublication.Tittle              = model.Tittle;
            resultPublication.Tradable            = model.Tradable;
            resultPublication.UserAddress         = model.UserAddress;
            resultPublication.InstrumentCondition = model.InstrumentCondition;
            resultPublication.InitialPrice        = model.InitialPrice;
            resultPublication.Category            = model.Category;
            return(Ok(resultPublication));
        }
Exemplo n.º 14
0
        public IActionResult deleteMainPicture(int publicationId, ImageName image)
        {
            try
            {
                int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (id == null)
                {
                    return(Unauthorized(new ErrorExceptionModel("Sem Autorização ou sem sessão inciada")));
                }
                PublicationDAO pDAO    = new PublicationDAO(_connection);
                bool           deleted = pDAO.deleteMainImage(publicationId, image);

                if (deleted == true)
                {
                    return(Ok("Imagem apagada!"));
                }
                else
                {
                    return(BadRequest("Imagem não apagada ou inexistente!"));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 15
0
        private void AuthorizeUser(AuthorizationContext context)
        {
            var organizationRequested = (string)context.RouteData.Values["organization"];
            var userOrganiation       = ClaimHelper.GetCurrentUserClaim(Fabrikam.ClaimTypes.Organization).Value;

            if (!organizationRequested.Equals(userOrganiation, StringComparison.OrdinalIgnoreCase))
            {
                context.Result = new HttpUnauthorizedResult();
                return;
            }

            var  authorizedRoles = this.Roles.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            bool hasValidRole    = false;

            foreach (var role in authorizedRoles)
            {
                if (context.HttpContext.User.IsInRole(role.Trim()))
                {
                    hasValidRole = true;
                    break;
                }
            }

            if (!hasValidRole)
            {
                context.Result = new HttpUnauthorizedResult();
                return;
            }
        }
Exemplo n.º 16
0
        public ActionResult CreateChat(int matchId)
        {
            int?userId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (userId == null)
            {
                return(Unauthorized(new ErrorMessageModel("Utilizador não tem autorização ou não existe!")));
            }

            try
            {
                ChatDAO chatDAO = new ChatDAO(_connection);

                if (chatDAO.getChatIdWithTargetUser((int)userId, matchId) == null)
                {
                    Chat chat = new Chat();
                    chat.UserId = (int)userId;
                    chat.ChatId = chatDAO.CreateChatId();

                    chatDAO.CreateChat(chat);

                    chat.UserId = matchId;
                    chatDAO.CreateChat(chat);

                    return(Ok(new SuccessMessageModel("Chat criado!")));
                }

                return(Ok(new SuccessMessageModel("O Chat já existe!")));
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 17
0
        protected async Task <IActionResult> RefreshUserToken(Guid userId)
        {
            // Look up the user by its refresh token
            var user = _userService.GetUserById(userId);

            if (user == null)
            {
                return(Ok(new { Errors = new[] { "UserNotExist" } }));
            }

            // Reject if user has been locked out
            if (user.LockoutEnd >= DateTimeOffset.UtcNow)
            {
                return(Ok(new { Errors = new[] { "UserLockedOut" } }));
            }

            // Get roles of current user
            var roles = await _userManager.GetRolesAsync(user);

            // Generate claims and JWT token
            var langs  = Utils.GetAllLanguages();
            var claims = ClaimHelper.GetClaims(user, roles, langs);

            // Generate token
            var token = TokenGenerator.Generate(claims, roles, _config, user.SecurityStamp);

            return(Ok(token));
        }
Exemplo n.º 18
0
        public ActionResult <Message> getLastMessageFromChat(int id)
        {
            int?userId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (userId == null)
            {
                return(Unauthorized(new ErrorMessageModel("Utilizador não tem autorização ou não existe!")));
            }

            try
            {
                ChatDAO chatDao = new ChatDAO(_connection);
                Message message = chatDao.GetLastMessageFromChat(id, (int)userId);

                if (message != null)
                {
                    return(Ok(message));
                }

                return(BadRequest(new ErrorMessageModel("Não existe connection ID!")));
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 19
0
        public ActionResult <bool> CreateChat(int matchId, int publicationId, string publicationName)
        {
            int?userId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

            if (userId == null)
            {
                return(Unauthorized(new ErrorExceptionModel("Utilizador não tem autorização!")));
            }

            UserDAO userDAO = new UserDAO(_connection);
            User    user    = userDAO.FindById(matchId);

            if (userId < 0)
            {
                return(UnprocessableEntity(new ErrorExceptionModel("Utilizador não existe!")));
            }

            Chat chat = new Chat();

            chat.UserId          = (int)userId;
            chat.PublicationId   = publicationId;
            chat.PublicationName = publicationName;
            ChatDAO chatDAO = new ChatDAO(_connection);

            chat.ChatId = chatDAO.CreateChatId();
            chatDAO.CreateChat(chat);

            chat.UserId = matchId;
            chatDAO.CreateChat(chat);

            return(Ok("Concluído!"));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Check if user is authorized on a given permissionKey
        /// </summary>
        private bool IsAuthorized(HttpContextBase httpContext)
        {
            if (httpContext.User != null && ClaimHelper.GetClaimToString(CaresUserClaims.UserDomainKey) == null)
            {
                httpContext.User = null;
                return(false);
            }

            if (httpContext.User != null && (httpContext.User.IsInRole("Admin") || httpContext.User.IsInRole("SystemAdministrator")))
            {
                return(true);
            }

            Claim serializedUserPermissionSet = ClaimHelper.GetClaimToString(CaresUserClaims.UserPermissionSet);

            if (serializedUserPermissionSet == null)
            {
                return(false);
            }
            var userPermissionSet = JsonConvert.DeserializeObject <List <string> >(serializedUserPermissionSet.Value);

            if (!userPermissionSet.Any())
            {
                return(false);
            }
            return(userPermissionSet.Any(userPSet => userPSet.Contains(PermissionKey)));
        }
Exemplo n.º 21
0
        public IActionResult UploadImagesToPost(int id,
                                                [FromForm] IFormFileCollection images,
                                                [FromForm] IFormFile mainImage)
        {
            try
            {
                int?employerID = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (employerID == null)
                {
                    return(Unauthorized(new ErrorMessageModel("Não Autorizado!")));
                }

                IJobDAO jobDAO = new JobDAO(_connection, this._environment.ContentRootPath);

                if (jobDAO.FindById(id, (int)employerID) == null)
                {
                    return(NotFound(new ErrorMessageModel("Post não encontrado!")));
                }

                SuccessMessageModel message = jobDAO.UploadImagesToPost(id, images, mainImage);

                return(Ok(message));
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorMessageModel(e.Message)));
            }
        }
Exemplo n.º 22
0
        private void SetExternalInvitationRoles(ApplicationUser externalUser, string phone)
        {
            //----------------------------------------------------------------------------------------------------
            // when the external user accepts the invitation, we remove the invitation and roles claims for the
            // internal user, confirm the email and add phone # for the external user.
            //----------------------------------------------------------------------------------------------------
            if (externalUser != null)
            {
                string   roleClaim = ClaimHelper.GetSafeClaim(externalUser, AppConstants.ROLES_CLAIM, string.Empty);
                string[] roles     = roleClaim.Split(new char[] { ',' });
                if (roles.Length > 0)
                {
                    _userManager.AddToRoles(externalUser.Id, roles);
                }

                externalUser.EmailConfirmed = true;
                externalUser.PhoneNumber    = phone;
                _userManager.Update(externalUser);

                // remove invitation claim for the internal user
                SafeRemoveClaim(externalUser, AppConstants.INVITATION_CLAIM, ClaimHelper.GetSafeClaim(externalUser, AppConstants.INVITATION_CLAIM, "1"));
                SafeRemoveClaim(externalUser, AppConstants.EXPIRATION_DATE_CLAIM, ClaimHelper.GetSafeClaim(externalUser, AppConstants.EXPIRATION_DATE_CLAIM, string.Empty));
                SafeRemoveClaim(externalUser, AppConstants.ROLES_CLAIM, ClaimHelper.GetSafeClaim(externalUser, AppConstants.ROLES_CLAIM, string.Empty));
            }
        }
Exemplo n.º 23
0
        public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
        {
            ClaimsPrincipal validatedToken = _tokenService.IsTokenAuthentic(request.Token);

            if (validatedToken == null)
            {
                return(BadRequest(new ErrorResponse {
                    Message = "This token has been tampered with."
                }));
            }

            RefreshToken refreshToken = await _tokenService.CanTokenBeRefreshedAsync(validatedToken, request.RefreshToken);

            if (refreshToken == null)
            {
                return(BadRequest(new ErrorResponse {
                    Message = "Invalid Token, cannot refresh."
                }));
            }

            string organisationID = ClaimHelper.GetNamedClaim(validatedToken, "OrganisationID");

            var transaction = _unitOfWork.RefreshTokenRepository.BeginTransaction();

            RefreshTokenResponse refreshTokenResponse = await _tokenService.RefreshTokenAsync(validatedToken, refreshToken, organisationID);

            transaction.Commit();

            return(Ok(new Response <RefreshTokenResponse>(refreshTokenResponse)));
        }
Exemplo n.º 24
0
 private string GetStartPage(string userName, bool useEmail = false)
 {
     ViewBag.StartPageClass = "fa-heart-o";
     try
     {
         ApplicationUser appUser = _userManager.FindByName(userName);
         if (useEmail)
         {
             appUser = _userManager.FindByEmail(userName);
         }
         if (appUser != null)
         {
             string page = ClaimHelper.GetSafeClaim(appUser, AppConstants.FAVORITE_PAGE);
             if (page != string.Empty)
             {
                 ViewBag.StartPageClass = "fa-heart red";
             }
             return(page);
         }
     }
     catch
     {
     }
     return(string.Empty);
 }
        public ActionResult AddClaimMapping()
        {
            // TODO: sanitize input and add AntiForgeryToken
            var incomingClaimType = this.Request.Form["IncomingClaimType"];
            var incomingValue     = this.Request.Form["IncomingValue"];
            var roleName          = this.Request.Form["NewRole"];
            var organization      = ClaimHelper.GetCurrentUserClaim(Fabrikam.ClaimTypes.Organization).Value;

            var claimMappingsRepository = new ClaimMappingRepository();
            var role = claimMappingsRepository.GetRoleByName(roleName);

            if (this.ValidateClaimMapping(incomingClaimType, incomingValue, role, organization, claimMappingsRepository))
            {
                claimMappingsRepository.SaveClaimMapping(
                    new ClaimMapping
                {
                    IncomingClaimType = incomingClaimType,
                    IncomingValue     = incomingValue,
                    OutputRole        = role,
                    Organization      = organization
                });
            }

            return(this.ClaimMappings());
        }
Exemplo n.º 26
0
        public ActionResult <List <JobPostReturnedModel> > GetAvailableWorks([FromQuery(Name = "categories")] Categories[] categories, [FromQuery(Name = "address")] string address, [FromQuery(Name = "distance")] int?distance, [FromQuery(Name = "rating")] int?rating)
        {
            try
            {
                int?mateID = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (mateID == null)
                {
                    return(NotFound(new ErrorMessageModel("Utilizador não existe!")));
                }

                MateDAO mateDao = new MateDAO(_connection);
                Mate    mate    = mateDao.FindMateById((int)mateID);

                if (address == null)
                {
                    address = mate.Address;
                }

                IJobDAO jobDAO = new JobDAO(_connection);
                List <JobPostReturnedModel> postsList = _mapper.Map <List <JobPostReturnedModel> >(jobDAO.GetJobs(categories, address, distance, rating, (int)mateID));

                return(Ok(postsList));
            }
            catch (Exception ex)
            {
                return(UnprocessableEntity(new ErrorMessageModel(ex.Message)));
            }
        }
Exemplo n.º 27
0
        public async Task <RefreshToken> CanTokenBeRefreshedAsync(ClaimsPrincipal validatedToken, string refreshToken)
        {
            long expiryDateUnix = ClaimHelper.GetUnixExpiryDate(validatedToken);

            //if not expired, dont let user refresh
            //tokens contain time in unix format.
            //unix epoch (1970 1 1 000) is used to calculate unix time
            //unix time (nr of seconds elapsed since epoch)
            DateTime expiryDateTimeUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                                         .AddSeconds(expiryDateUnix);

            RefreshToken storedRefreshToken = await _unitOfWork.RefreshTokenRepository.GetRefreshToken(refreshToken);

            if (expiryDateTimeUtc > DateTime.UtcNow ||
                storedRefreshToken == null ||
                DateTime.UtcNow > storedRefreshToken.ExpiryDate ||
                storedRefreshToken.Invalidated ||
                storedRefreshToken.Used ||
                storedRefreshToken.JwtID != ClaimHelper.GetJTI(validatedToken))
            {
                return(null);
            }

            return(storedRefreshToken);
        }
Exemplo n.º 28
0
        public JsonResult Retrieve()
        {
            if (_userManager != null && _userManager.SupportsUserRole)
            {
                var appUsers      = _userManager.Users.ToList();
                var filteredUsers = appUsers.Where(u => u.Claims.Any(t => t.ClaimType == AppConstants.INVITATION_CLAIM && t.ClaimValue == "1"));
                var invitedUsers  = filteredUsers.Select(u =>
                                                         new UserInvitationViewModel
                {
                    UserId          = u.Id,
                    UserName        = u.UserName,
                    UserEmail       = u.Email,
                    InvitationCode  = ClaimHelper.GetSafeClaim(u, AppConstants.INVITATION_CODE_CLAIM, string.Empty),
                    ExpirationDate  = DateTime.Parse(ClaimHelper.GetSafeClaim(u, AppConstants.EXPIRATION_DATE_CLAIM, DateTime.Today.Date.AddDays(-1).ToShortDateString())),
                    UserRoles       = TuplifyString(ClaimHelper.GetSafeClaim(u, AppConstants.ROLES_CLAIM, string.Empty)),
                    Password        = string.Empty,
                    ConfirmPassword = string.Empty,
                })
                                    .ToList();

                string message = string.Format("Total of {0:d} users are retrieved for invitation.", invitedUsers.Count());
                DojoLogger.Trace(message, typeof(UserRoleManagerController));

                return(Json(invitedUsers, JsonRequestBehavior.AllowGet));
            }
            else if (!_userManager.SupportsUserRole)
            {
                return(JsonError("User Role is not suported."));
            }
            else
            {
                return(JsonError("Role manager does not exist"));
            }
        }
        private static void AddOrUpdateClaims(User user, ClaimsPrincipal UserClaimsPrincipal)
        {
            var existingPasswordIsAboutToExpireClaim = ClaimHelper.GetClaim(UserClaimsPrincipal,
                                                                            CustomClaimTypes.PasswordIsAboutToExpire);

            if (existingPasswordIsAboutToExpireClaim != null)
            {
                ((ClaimsIdentity)UserClaimsPrincipal.Identity).RemoveClaim(existingPasswordIsAboutToExpireClaim);
            }

            ((ClaimsIdentity)UserClaimsPrincipal.Identity).AddClaim(new Claim(CustomClaimTypes.PasswordIsAboutToExpire,
                                                                              JsonConvert.SerializeObject(user.PasswordIsAboutToExpire)));

            var existingPasswordExpiryDaysRemaining = ClaimHelper.GetClaim(UserClaimsPrincipal,
                                                                           CustomClaimTypes.PasswordExpiryDaysRemaining);

            if (existingPasswordExpiryDaysRemaining != null)
            {
                ((ClaimsIdentity)UserClaimsPrincipal.Identity).RemoveClaim(existingPasswordExpiryDaysRemaining);
            }

            ((ClaimsIdentity)UserClaimsPrincipal.Identity).AddClaim(
                new Claim(CustomClaimTypes.PasswordExpiryDaysRemaining,
                          JsonConvert.SerializeObject(user.PasswordExpiryDaysRemaining)));
        }
Exemplo n.º 30
0
        private Guid GetUserId()
        {
            Guid userId;

            Guid.TryParse(ClaimHelper.GetClaimValue(Context.User, ClaimTypes.Sid), out userId);
            return(userId);
        }