Exemple #1
0
 public SignController(JwtTokenManager tokenManager, IRoleStore roleStore, UserRepository userRepository, IUnitOfWorkFactory unitOfWorkFactory)
 {
     _tokenManager      = tokenManager;
     _roleStore         = roleStore;
     _userRepository    = userRepository;
     _unitOfWorkFactory = unitOfWorkFactory;
 }
        public IHttpActionResult GetCity(RequestModel requestModel)

        {
            //var data = requestModel.Data;
            //DropDownModel objDropDownModel = JsonConvert.DeserializeObject<DropDownModel>(data);
            //var sendResponse = new ResponseModel() { Response = JsonConvert.SerializeObject(userServices.GetCity(objDropDownModel)), Success = true };
            //var sendJson = Json(sendResponse);
            //return sendJson;

            var data = new JwtTokenManager().DecodeToken(requestModel.Data);
            Dictionary <string, object> request = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);

            if (request.ContainsKey("unique_name"))
            {
                DropDownModel objDropDownModel = JsonConvert.DeserializeObject <DropDownModel>(request["unique_name"].ToString());
                return(Json(new ResponseModel()
                {
                    Response = new JwtTokenManager().GenerateToken(JsonConvert.SerializeObject(userServices.GetCity(objDropDownModel))), Success = true
                }));
            }
            return(Json(new ResponseModel()
            {
                Response = BadRequest().ToString(), Success = false
            }));
        }
        public IHttpActionResult SaveBusiness(RequestModel requestModel)
        {
            var data = new JwtTokenManager().DecodeToken(requestModel.Data);
            Dictionary <string, object> request = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);

            if (request.ContainsKey("unique_name"))
            {
                BusinessModel objBusinessProfile = JsonConvert.DeserializeObject <BusinessModel>(request["unique_name"].ToString());
                return(Json(new ResponseModel()
                {
                    Response = new JwtTokenManager().GenerateToken(JsonConvert.SerializeObject(userServices.SaveBusiness(objBusinessProfile))), Success = true
                }));
            }
            return(Json(new ResponseModel()
            {
                Response = BadRequest().ToString(), Success = false
            }));



            /*
             * var data = requestModel.Data;
             * BusinessModel objUserProfile = JsonConvert.DeserializeObject<BusinessModel>(data);
             * var sendResponse = new ResponseModel() { Response = JsonConvert.SerializeObject(userServices.SaveBusiness(objUserProfile)), Success = true };
             * var sendJson = Json(sendResponse);
             * return sendJson;
             */
        }
Exemple #4
0
        public HttpResponseMessage Get([FromUri] int currentPage = 1, [FromUri] int pageSize = 0, [FromUri] string query = "", [FromUri] string sort = "")
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.ACCOUNT_VIEW_LIST);

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId       = Convert.ToInt32(payload["id"]);
                    var isAuthorized = _authorizationService.Authorize(userId);
                    if (isAuthorized)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        responseData        = ResponseFormat.Success;
                        var sortQ = new List <string>();
                        sortQ             = sort.Split(',').ToList();
                        responseData.data = _accountService.GetAccountList(query, pageSize, currentPage, sortQ);
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
        public IHttpActionResult ForgetPassword(RequestModel requestModel)
        {
            var data = new JwtTokenManager().DecodeToken(requestModel.Data);
            Dictionary <string, object> request = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);

            if (request.ContainsKey("unique_name"))
            {
                LoginModel objLoginModel = JsonConvert.DeserializeObject <LoginModel>(request["unique_name"].ToString());
                return(Json(new ResponseModel()
                {
                    Response = new JwtTokenManager().GenerateToken(JsonConvert.SerializeObject(userServices.ForgetPassword(objLoginModel))), Success = true
                }));
            }
            return(Json(new ResponseModel()
            {
                Response = BadRequest().ToString(), Success = false
            }));


            #region Using Json

            /*
             * var data = requestModel.Data;
             * LoginModel objLoginModel = JsonConvert.DeserializeObject<LoginModel>(data);
             * var sendResponse = new ResponseModel() { Response = JsonConvert.SerializeObject(userServices.ForgetPassword(objLoginModel)), Success = true };
             * var sendJson = Json(sendResponse);
             * return sendJson;
             */
            #endregion
        }
Exemple #6
0
        public async Task <LoginResponse> Login([FromBody] LoginRequest loginRequest)
        {
            var response = new LoginResponse();

            try
            {
                if (loginRequest == null || (string.IsNullOrWhiteSpace(loginRequest.Username) || string.IsNullOrWhiteSpace(loginRequest.Password)))
                {
                    throw new APIException("Credentials cannot be null");
                }

                string         error    = string.Empty;
                ClaimsIdentity identity = await GetClaimsIdentity(loginRequest, out error);

                var jwtSecurityToken = await JwtTokenManager.GetJwtTokenForIdentity(loginRequest, identity);

                response.Token   = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                response.Expires = jwtSecurityToken.ValidTo;
                SaveResponseOfClient(response);
                response.IsSuccess    = true;
                response.ErrorMessage = error;
                response.Name         = identity.FindFirst("Name").Value;
            }
            catch (Exception ex)
            {
                response.IsSuccess    = false;
                response.ErrorMessage = "Login failed.";
                LogException(IdentityServer.API.EventIds.Login, ex);
            }

            return(response);
            //--validation
        }
Exemple #7
0
        public HttpResponseMessage Detail([FromUri] int id)
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.TASK_VIEW);
            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = payload["id"];

                    var isAuthorized = _authorizationService.Authorize(Convert.ToInt32(userId));
                    if (isAuthorized)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        responseData        = ResponseFormat.Success;
                        responseData.data   = _taskTemplateService.GetTask(id);
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
 protected override string Serialize()
 {
     return(JsonConvert.SerializeObject(new
     {
         access_token = JwtTokenManager.GenerateToken(ClientId),
         token_type = "jwt",
         expire_in = this.Lifetime
     }));
 }
        public void TestThatGetSymmetricSecurityKeyLoadsKeyFromConfiguration()
        {
            //arrange
            var sut = new JwtTokenManager(authSettingsOption, userManager);

            //act
            sut.GetSymmetricSecurityKey();
            //assert
            A.CallTo(() => authenticationSettings.SymmetricSecurityKey).MustHaveHappened();
        }
Exemple #10
0
        protected Task <IPrincipal> AuthJwtToken(string token)
        {
            IEnumerable <Claim> claims;

            if (JwtTokenManager.ValidateToken(token, _Configuration.GetSection("JWTAudience").Key, _Configuration.GetSection("SelfAddress").Key, out claims))
            {
                var        identity = new ClaimsIdentity(claims.ToList(), "Jwt");
                IPrincipal user     = new ClaimsPrincipal(identity);
                return(Task.FromResult(user));
            }
            return(Task.FromResult <IPrincipal>(null));
        }
        public async Task TestThatCreationOfARefreshTokenUpdatesTheUserInTheDatabase()
        {
            //arrange
            var sut      = new JwtTokenManager(authSettingsOption, userManager);
            var username = "******";
            //act
            await sut.GenerateTokenResponse(username);

            //assert
            A.CallTo(() => userManager.UpdateRefreshTokenForUser(username, A <string> .Ignored))
            .MustHaveHappenedOnceExactly();
        }
Exemple #12
0
 /// <summary>
 /// validate that the token has a valid signature
 /// </summary>
 /// <returns>true if the signature is valid, false otherwise</returns>
 public bool SignatureValid()
 {
     try
     {
         var tokenManager = new JwtTokenManager(new LicenseSigningParameters(PublicKey));
         tokenManager.ParseSecurityToken <object>(LicenseData);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemple #13
0
        public IHttpActionResult GetProduct(RequestModel requestModel)

        {
            var          data            = new JwtTokenManager().DecodeToken(requestModel.Data);
            ProductModel objProductModel = JsonConvert.DeserializeObject <ProductModel>(data);

            return(Json(new ResponseModel()
            {
                Response = new JwtTokenManager()
                           .GenerateToken(
                    JsonConvert.SerializeObject(
                        userServices.GetProduct(objProductModel))),
                Success = true
            }));
        }
Exemple #14
0
        public HttpResponseMessage ResetPassword([FromUri] string email)
        {
            //_emailManager = new EmailManager()
            HttpResponseMessage response = new HttpResponseMessage();

            ResponseFormat responseData;

            var dbUser = db.USERs.Where(c => c.Email == email).FirstOrDefault();

            if (dbUser != null)
            {
                Random r = new Random();
                string validationCode = r.Next(10000, 1000000).ToString("D6");
                var    jwtManager     = JwtTokenManager.GenerateJwtForPasswordReset(validationCode, email);

                _emailManager            = new EmailManager();
                _emailManager.Title      = StaticStrings.RESET_PASSWORD_TITLE;
                _emailManager.Content    = $"<a style='-webkit-appearance:button; -moz-appearance:button; appearance:button; text-decoration:none; background-color: #D93915; color: white; padding: 1em 1.5em; text-transform: uppercase;' href='{StaticStrings.ClientHost}reset_password?key={jwtManager}'>Reset password</a><p style='font-style: italic;'>This link will expire after 30 minutes.</p>";
                _emailManager.Recipients = new List <string>()
                {
                    email
                };
                _emailManager.SendEmail();
                if (_emailManager.isSent)
                {
                    dbUser.RememberMeToken = validationCode;
                    db.SaveChanges();
                    response.StatusCode = HttpStatusCode.OK;
                    responseData        = ResponseFormat.Success;
                }
                else
                {
                    response.StatusCode  = HttpStatusCode.InternalServerError;
                    responseData         = ResponseFormat.Fail;
                    responseData.message = ErrorMessages.EMAIL_SEND_FAILED;
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.NotFound;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.USER_NOT_FOUND;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
        public async Task TestThatCreateTokenUsesTheExpiryTimeFromTheConfig()
        {
            //arrange
            var sut = new JwtTokenManager(authSettingsOption, userManager);
            //act
            var token = await sut.CreateToken("username");

            //assert
            A.CallTo(() => authenticationSettings.TokenExpiryMinutes).MustHaveHappened();
            //We calculate approx when we would expect the token to expire,
            //a tolerance of 5 seconds is allowed to allow for a slow running test etc.
            var approxExpectedValidToTime = DateTime.Now.AddMinutes(10);
            var timeDifference            = approxExpectedValidToTime.Subtract(token.ValidTo);

            Assert.True(timeDifference.Seconds < 5);
        }
Exemple #16
0
        public HttpResponseMessage Get(string query = "")
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    response.StatusCode = HttpStatusCode.OK;
                    responseData        = ResponseFormat.Success;
                    var tags = _tagService.GetTagList(query);
                    responseData.data = tags;
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
        public IActionResult GetUser([FromBody] User u)
        {
            IActionResult msg = null;

            try
            {
                User user = this._userRepository.GetUser(u.username, u.password);
                user.Token = JwtTokenManager.GenerateToken(user.username, user.Uniquekey, _configuration);
                msg        = Ok(user);
            }
            catch (Exception ex)
            {
                //msg = HttpContext.Response.StatusCode.
                msg = BadRequest(ex.ToString());
            }
            return(msg);
        }
Exemple #18
0
        public static ResponseModel GetApiResponseJWT(string Url, String Data)
        {
            JwtTokenManager _JwtTokenManager = new JwtTokenManager();
            var             _response        = Services.GetApiResponseJson(Url, "POST", Data);

            ResponseModel _dataApi = JsonConvert.DeserializeObject <ResponseModel>(_response);

            dynamic _data = _JwtTokenManager.DecodeToken(_dataApi.Response);
            var     json  = JsonConvert.DeserializeObject <Dictionary <string, object> >(_data);

            if (json.ContainsKey("unique_name"))
            {
                ResponseModel objRespMOdel = JsonConvert.DeserializeObject <ResponseModel>(json["unique_name"]);
                //var responeSend = objRespMOdel.Response;
                return(objRespMOdel);
            }
            return(new ResponseModel());
        }
Exemple #19
0
        public static List <AddToCartModel> GetMyCart(HttpContextBase httpContext, JwtTokenManager jwtTokenManager)
        {
            List <AddToCartModel> myCart = new List <AddToCartModel>();

            if (Services.GetCookie(httpContext, "addtocart") == null)
            {
                return(myCart);
            }
            string  cookiesValue = Services.GetCookie(httpContext, "addtocart").Value;
            dynamic _data        = jwtTokenManager.DecodeToken(cookiesValue);
            var     json         = JsonConvert.DeserializeObject <Dictionary <string, object> >(_data);

            if (json.ContainsKey("unique_name"))
            {
                myCart = JsonConvert.DeserializeObject <List <AddToCartModel> >(json["unique_name"].ToString());
            }
            return(myCart);
        }
Exemple #20
0
        public static LoginModel GetLoginUser(HttpContextBase httpContext, JwtTokenManager jwtTokenManager)
        {
            LoginModel login = new LoginModel();

            if (Services.GetCookie(httpContext, "usr") == null)
            {
                return(login);
            }
            string  cookiesValue = Services.GetCookie(httpContext, "usr").Value;
            dynamic _data        = jwtTokenManager.DecodeToken(cookiesValue);
            var     json         = JsonConvert.DeserializeObject <Dictionary <string, object> >(_data);

            if (json.ContainsKey("unique_name"))
            {
                login = JsonConvert.DeserializeObject <LoginModel>(json["unique_name"].ToString());
            }
            return(login);
        }
Exemple #21
0
        public IHttpActionResult SaveUserForgetPasswordLink(RequestModel requestModel)
        {
            var data = new JwtTokenManager().DecodeToken(requestModel.Data);
            Dictionary <string, object> request = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);

            if (request.ContainsKey("unique_name"))
            {
                LoginModel objLoginModel = JsonConvert.DeserializeObject <LoginModel>(request["unique_name"].ToString());
                return(Json(new ResponseModel()
                {
                    Response = new JwtTokenManager().GenerateToken(JsonConvert.SerializeObject(userServices.SaveUserForgetPasswordLink(objLoginModel))), Success = true
                }));
            }
            return(Json(new ResponseModel()
            {
                Response = BadRequest().ToString(), Success = false
            }));
        }
Exemple #22
0
        public AccountService(
            IAccountRepository accountRepository,
            IHistoryService historyService,
            IHttpContextAccessor httpContextAccessor,
            UserManager <TUser> userManager,
            RoleManager <TRole> roleManager,
            IMapper mapper,
            JwtTokenManager jwtTokenManager)
        {
            this.accountRepository   = accountRepository;
            this.historyService      = historyService;
            this.httpContextAccessor = httpContextAccessor;
            this.userManager         = userManager;
            this.roleManager         = roleManager;
            this.mapper          = mapper;
            this.jwtTokenManager = jwtTokenManager;

            this.mapDataToDomain = this.mapper.Map <Data.Account, Core.Account>;
        }
        /// <summary>
        /// Configure Authentication and JwtBearer extensions
        /// </summary>
        /// <param name="services"></param>
        /// <param name="jwtTokenParameters"></param>
        /// <param name="authSetup"></param>
        /// <param name="jwtSetup"></param>
        public static void AddJwtAuthentication(this IServiceCollection services, JwtTokenParameters jwtTokenParameters, Action <AuthenticationOptions> authSetup, Action <JwtBearerOptions> jwtSetup = null)
        {
            services.AddScoped(s => new JwtTokenManager(jwtTokenParameters));
            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                authSetup?.Invoke(o);
            })
            .AddJwtBearer(options =>
            {
                options.Audience     = jwtTokenParameters.Audience;
                options.ClaimsIssuer = jwtTokenParameters.Issuer;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = jwtTokenParameters.Issuer,
                    ValidAudience            = jwtTokenParameters.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenParameters.GetSymetricSecurityKey(),
                    ValidateLifetime         = true,
                };
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        // Add the access_token as a claim, as we may actually need it
                        if (context.SecurityToken is JwtSecurityToken token && jwtTokenParameters.SendNewKeyInEveryResponse)
                        {
                            var manager  = new JwtTokenManager(jwtTokenParameters);
                            var newToken = manager.CreateNewToken(token.Claims);
                            context.Response.Headers.Add("tokenValue", newToken.Value);
                            context.Response.Headers.Add("tokenExpiration", newToken.Expiration.ToString("s") + "Z");
                        }
                        return(Task.CompletedTask);
                    }
                };

                jwtSetup?.Invoke(options);
            });
        }
Exemple #24
0
        public VerifyResponse Verify([FromBody] VerifyRequest verifyRequest)
        {
            var response = new VerifyResponse();

            try
            {
                if (verifyRequest == null || string.IsNullOrWhiteSpace(verifyRequest.Token))
                {
                    throw new APIException("Token cannot be null");
                }

                LoginResponse loginResponse = null;
                loginResponse = Storage.IssuedTokens.SingleOrDefault(t => t.Token == verifyRequest.Token);
                if (loginResponse != null)
                {
                    if (JwtTokenManager.ValidateToken(loginResponse.Token))
                    {
                        response.IsSuccess = true;
                    }
                    else
                    {
                        response.IsSuccess    = false;
                        response.ErrorMessage = "Invalid token.";
                    }
                }
                else
                {
                    response.IsSuccess    = false;
                    response.ErrorMessage = "User not authenticated.";
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess    = false;
                response.ErrorMessage = "Verification failed.";
                LogException(IdentityServer.API.EventIds.Verify, ex);
            }
            return(response);
        }
Exemple #25
0
        public HttpResponseMessage AddContacts([FromUri] int id, [FromBody] AccountAddContactApiModel contact)
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();
            //AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_MODIFY);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId       = Convert.ToInt32(payload["id"]);
                    var owner        = _accountService.FindOwnerId(id);
                    var collaborator = _accountService.FindCollaboratorId(id);
                    if ((userId == owner) || (userId == collaborator) || (new AuthorizationService().SetPerm((int)EnumPermissions.ACCOUNT_DELETE).Authorize(userId)))
                    {
                        var isAdded = _accountService.AddContact(id, contact.id);
                        if (isAdded)
                        {
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.CONTACT_ADDED;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.InternalServerError;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.SOMETHING_WRONG;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Exemple #26
0
        public HttpResponseMessage CreateNote([FromUri] int id)
        {
            var                  response     = new HttpResponseMessage();
            ResponseFormat       responseData = new ResponseFormat();
            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.NOTE_CREATE);
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId       = Convert.ToInt32(payload["id"]);
                    var isAuthorized = _authorizationService.Authorize(userId);
                    if (isAuthorized)
                    {
                        string noteBody = HttpContext.Current.Request.Form["body"];
                        if (!string.IsNullOrEmpty(noteBody))
                        {
                            //create a note
                            NoteApiModel apiModel = new NoteApiModel();
                            apiModel.body      = noteBody;
                            apiModel.createdBy = new UserLinkApiModel()
                            {
                                id = userId
                            };
                            apiModel.account = id;
                            var createdNote = _noteService.Create(apiModel);

                            //create files and link them to note
                            if (HttpContext.Current.Request.Files.Count > 0)
                            {
                                var allFiles = HttpContext.Current.Request.Files;
                                foreach (string fileName in allFiles)
                                {
                                    HttpPostedFile   uploadedFile = allFiles[fileName];
                                    FileManager.File file         = new FileManager.File(uploadedFile);
                                    _noteService.AddFile(createdNote, file);
                                }
                            }
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.NOTE_ADDED;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.BadRequest;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.NOTE_EMPTY;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Exemple #27
0
        public HttpResponseMessage Delete([FromUri] int id)
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();
            //AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_MODIFY);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = Convert.ToInt32(payload["id"]);
                    var owner  = _taskTemplateService.GetTaskOwner(id);
                    if ((userId == owner) || (new AuthorizationService().SetPerm((int)EnumPermissions.TASK_DELETE_ANY).Authorize(userId)))
                    {
                        var isRemoved = _taskTemplateService.DeleteTask(id);
                        if (isRemoved)
                        {
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.TASK_DELETED;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.InternalServerError;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.SOMETHING_WRONG;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Exemple #28
0
        public HttpResponseMessage ChangeAvatar([FromUri] int id)
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();
            //read jwt
            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = Convert.ToInt32(payload["id"]);
                    //if user is owner
                    var owner        = _contactService.FindOwnerId(id);
                    var collaborator = _contactService.FindCollaboratorId(id);
                    if ((userId == owner) || (userId == collaborator) || (new AuthorizationService().SetPerm((int)EnumPermissions.CONTACT_DELETE).Authorize(userId)))
                    {
                        if (HttpContext.Current.Request.Files.Count > 0)
                        {
                            var uploadedFile = HttpContext.Current.Request.Files[0];
                            var isChanged    = _contactService.ChangeAvatar(id, uploadedFile);
                            if (isChanged)
                            {
                                response.StatusCode  = HttpStatusCode.OK;
                                responseData         = ResponseFormat.Success;
                                responseData.message = SuccessMessages.AVATAR_CHANGED;
                            }
                            else
                            {
                                response.StatusCode  = HttpStatusCode.InternalServerError;
                                responseData         = ResponseFormat.Fail;
                                responseData.message = ErrorMessages.SOMETHING_WRONG;
                            }
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.BadRequest;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.INVALID_BODY;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Exemple #29
0
        public HttpResponseMessage Login([FromBody] LoginApiModel apiModel)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            ResponseFormat responseData;

            if (apiModel == null)
            {
                response.StatusCode  = HttpStatusCode.BadRequest;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.INVALID_BODY;
            }
            else
            {
                var validate = _userService.ValidatePassword(apiModel.email, apiModel.password);
                if (validate.Item1 == true)
                {
                    var dbUser = _userRepository.GetByEmail(validate.Item3.Email);
                    //generate jwt token
                    var JwtToken = JwtTokenManager.GenerateJwtToken(validate.Item3);
                    //generate refresh token
                    var           RefreshToken    = JwtTokenManager.GenerateRefreshToken();
                    REFRESH_TOKEN newRefreshToken = new REFRESH_TOKEN();
                    newRefreshToken.USER_ID = dbUser.ID;
                    newRefreshToken.Token   = RefreshToken;
                    db.REFRESH_TOKEN.Add(newRefreshToken);
                    db.SaveChanges();

                    //set refresh token to httponly and add it to cookies
                    //var nv = new NameValueCollection();
                    //nv["refreshToken"] = RefreshToken;
                    //nv["seriesIdentifier"] = dbUser.ID.ToString();
                    //nv["tokenIdentifier"] = newRefreshToken.ID.ToString();
                    response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={newRefreshToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");

                    //create response data
                    responseData = ResponseFormat.Success;
                    if (dbUser.Avatar != null)
                    {
                        responseData.data = new
                        {
                            user = new
                            {
                                id        = validate.Item3.ID,
                                username  = validate.Item3.Username,
                                firstName = validate.Item3.FirstName,
                                lastName  = validate.Item3.LastName,
                                jwt       = JwtToken,
                                group     = dbUser.GROUP.ID,
                                avatar    = $"{StaticStrings.ServerHost}avatar?fileName={dbUser.Avatar}"
                            }
                        };
                    }
                    else
                    {
                        responseData.data = new
                        {
                            user = new
                            {
                                id        = validate.Item3.ID,
                                username  = validate.Item3.Username,
                                firstName = validate.Item3.FirstName,
                                lastName  = validate.Item3.LastName,
                                jwt       = JwtToken,
                                group     = dbUser.GROUP.ID,
                                avatar    = ""
                            }
                        };
                    }

                    if (string.IsNullOrEmpty(dbUser.CalendarId))
                    {
                        try
                        {
                            var calId = googleCalendar.AddCalendar(dbUser.Email);
                            googleCalendar.AddPeopleToAcl(dbUser.Email, calId, true);
                            _userService.UpdateCalendarId(dbUser.Email, calId);
                        }
                        catch
                        {
                        }
                    }
                    response.StatusCode = HttpStatusCode.OK;
                }
                else
                {
                    response.StatusCode  = HttpStatusCode.Unauthorized;
                    responseData         = ResponseFormat.Fail;
                    responseData.message = validate.Item2;
                }
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Exemple #30
0
        public IHttpActionResult SaveUserProfile(RequestModel requestModel)
        {
            #region Comment Code For DataSet To Json
            //DataTable dt = new DataTable();
            //dt.Clear();
            //dt.Columns.Add("UserId");
            //dt.Columns.Add("InterestId");
            //dt.Columns.Add("InterestCatId");
            //DataRow _ravi;
            //_ravi = dt.NewRow();
            //_ravi["UserId"] = "1";
            //_ravi["InterestId"] = "2";
            //_ravi["InterestCatId"] = "3";
            //dt.Rows.Add(_ravi);
            //_ravi = dt.NewRow();
            //_ravi["UserId"] = "1";
            //_ravi["InterestId"] = "3";
            //_ravi["InterestCatId"] = "4";
            //dt.Rows.Add(_ravi);
            //_ravi = dt.NewRow();
            //_ravi["UserId"] = "1";
            //_ravi["InterestId"] = "4";
            //_ravi["InterestCatId"] = "5";
            //dt.Rows.Add(_ravi);
            //_ravi = dt.NewRow();
            //_ravi["UserId"] = "1";
            //_ravi["InterestId"] = "6";
            //_ravi["InterestCatId"] = "7";
            //dt.Rows.Add(_ravi);

            //string JSONresult;
            //JSONresult = JsonConvert.SerializeObject(dt);
            #endregion

            #region Comment Code For jsonToDataTable
            // List<UserInterestModel> usersList = JsonConvert.DeserializeObject<List<UserInterestModel>>(JSONresult);
            //DataTable dt1= CovnertJsonToDataTable.ToDataTable<UserInterestModel>(usersList);
            #endregion

            var data = new JwtTokenManager().DecodeToken(requestModel.Data);
            Dictionary <string, object> request = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);
            if (request.ContainsKey("unique_name"))
            {
                UserProfileModel objUserProfile = JsonConvert.DeserializeObject <UserProfileModel>(request["unique_name"].ToString());
                return(Json(new ResponseModel()
                {
                    Response = new JwtTokenManager().GenerateToken(JsonConvert.SerializeObject(userServices.SaveProfile(objUserProfile))), Success = true
                }));
            }
            return(Json(new ResponseModel()
            {
                Response = BadRequest().ToString(), Success = false
            }));

            #region Using Json Reponse

            /*
             * var data = requestModel.Data;
             * UserProfileModel objUserProfile = JsonConvert.DeserializeObject<UserProfileModel>(data);
             * var sendResponse = new ResponseModel() { Response = JsonConvert.SerializeObject(userServices.SaveProfile(objUserProfile)), Success = true };
             * var sendJson = Json(sendResponse);
             * return sendJson;
             */
            #endregion
        }