Example #1
0
        public async Task <RefreshTokenResponseData> RefreshToken(RefreshTokenRequestData model, string ip)
        {
            var             refreshTokenLifeTime = ValidateClientAuthentication(model.ClientId, model.ClientSecret);
            ClaimsPrincipal principal            = null;

            try
            {
                principal = TokenUtility.GetPrincipalFromExpiredToken(_appConfig.GetSection("AppConfiguration"), model.Token);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Token Error: Invalid token");
            }
            var username          = principal.Identity.Name;
            var savedRefreshToken = await _authTokenServ.GetRefreshToken(model.ClientId, username, model.RefreshToken);

            if (savedRefreshToken == null)
            {
                throw new ApplicationException("Token Error: Invalid refresh token");
            }

            var newJwtToken     = TokenUtility.GenerateJwtSecurityToken(_appConfig.GetSection("AppConfiguration"), principal.Claims);
            var newRefreshToken = TokenUtility.GenerateRefreshToken();
            await _authTokenServ.RemoveRefreshToken(savedRefreshToken);

            await SaveRefreshToken(model.ClientId, username, newRefreshToken, refreshTokenLifeTime, ip);

            return(new RefreshTokenResponseData()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(newJwtToken),
                TokenExpires = newJwtToken.ValidTo,
                TokenIssued = newJwtToken.ValidFrom,
                RefreshToken = newRefreshToken
            });
        }
Example #2
0
        public ActionResult Index()
        {
            var sharePointContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = sharePointContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    var currentUser = clientContext.Web.CurrentUser;

                    clientContext.Load(currentUser, user => user.Title);

                    clientContext.ExecuteQuery();

                    this.ViewBag.UserName = currentUser.Title;

                    this.ViewBag.SPHostUrl = sharePointContext.SPHostUrl;

                    // Save the token for Token Utility
                    var token = new TokenUtility().GetContextTokenFromRequest(this.HttpContext);

                    // Can I get the client's TenantId for licensing validation.
                    var    realm       = TokenHelper.GetRealmFromTargetUrl(sharePointContext.SPHostUrl);
                    string xrsTenantId = "c81ab8f0-183e-44c1-9faf-54c1f6a6f3d7";
                    System.Diagnostics.Debug.Assert(realm == xrsTenantId, "Found XRS Tenant Id!");

                    this.ViewBag.TenantId = realm;
                }
            }

            return(this.View());
        }
Example #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbInitializer dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseIdentity();
            app.UseCors("AllowAllHeaders");

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = TokenUtility.BuildTokenValidationParameters(Configuration.GetSection("AppConfiguration"))
            });

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwaggerDocumentation();

            // uncomment below code to run seed methods on startup
            // dbSeeder.Seed().Wait();
        }
Example #4
0
        private static void process(Object source, EventArgs args)
        {
            HttpApplication application = (HttpApplication)source;

            HttpContext context = application.Context;

            string token = context.Request["SSOToken"] == null ? context.Request.Headers["SSOToken"] : context.Request["SSOToken"];

            string extensionName = Path.GetExtension(context.Request.Url.LocalPath).ToLower();
            string loginUrl      = CubeConfig.LoginUrl;

            if (
                (extensionName == ".aspx" || extensionName == ".asmx" ||
                 context.Request.CurrentExecutionFilePathExtension == ".aspx" || context.Request.CurrentExecutionFilePathExtension == ".asmx")
                &&
                !CubeHttpModule.UnCheckUrlList.Exists(u => context.Request.Url.ToString().ToUpper().Contains(u.ToUpper()))
                )
            //!context.Request.Url.ToString().ToUpper().Contains(loginUrl.ToUpper()))
            {
                if (String.IsNullOrEmpty(token) || !TokenUtility.ValidToken(System.Web.HttpUtility.UrlDecode(token)))
                {
                    #if DEBUG
                    loginUrl += (loginUrl.Contains("?") ? "&" : "?") + "IsDebug=Y&LocalDebugUrl=" + System.Web.HttpUtility.UrlEncode(context.Request.Url.ToString());
                    #endif
                    if (extensionName == ".aspx" || context.Request.CurrentExecutionFilePathExtension.ToLower() == ".aspx")
                    {
                        context.Response.Redirect(loginUrl);
                    }
                }
            }
        }
Example #5
0
        public async Task <ActionResult <RefreshTokenResponse> > RefreshToken(RefreshTokenRequest request)
        {
            var principal = TokenUtility.GetClaimsPrincipal(request.OldToken);
            var userName  = principal.Identity.Name;
            var userData  = await _userRepository.FindUserByUserName(userName);

            if (userData != null && userData.RefreshToken.Equals(request.RefreshToken))
            {
                userData.RefreshToken = TokenUtility.GenerateRefreshToken();
                await _userRepository.Update(userData);

                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userData.UserName),
                };

                claims.AddRange(await _userRepository.GetUserClaims(userData));

                var token    = TokenUtility.GenerateToken(claims);
                var response = new LoginResponse
                {
                    Token          = token,
                    RefreshToken   = userData.RefreshToken,
                    ExpirationDate = DateTime.Now.AddMinutes(60).ToString("g")
                };

                return(Ok(response));
            }

            return(Unauthorized());
        }
Example #6
0
        public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            HttpContext context = application.Context;

            string token = (context.Request["SSOToken"] == null || context.Request["SSOToken"] == "null")
                ? context.Request.Headers["SSOToken"] : context.Request["SSOToken"];

            string extensionName = Path.GetExtension(context.Request.Url.LocalPath);
            string loginUrl      = CubeConfig.LoginUrl;

            if (extensionName == ".aspx" || extensionName == ".asmx" ||
                context.Request.CurrentExecutionFilePathExtension == ".aspx" || context.Request.CurrentExecutionFilePathExtension == ".asmx" &&
                !context.Request.Url.ToString().ToUpper().Contains(loginUrl.ToUpper()))
            {
                if (String.IsNullOrEmpty(token) || !TokenUtility.ValidToken(System.Web.HttpUtility.UrlDecode(token)))
                {
#if DEBUG
                    loginUrl += loginUrl.Contains("?") ? "&" : "?" + "IsDebug=Y&LocalDebugUrl=" + System.Web.HttpUtility.UrlEncode(context.Request.Url.ToString());
                    //context.Request.Headers.Add("IsDebug", "Y");
                    //context.Request.Headers.Add("LocalDebugUrl", context.Request.Url.ToString());
#endif
                    context.Response.Redirect(loginUrl);
                }
            }
        }
Example #7
0
        public async Task <IActionResult> SignIn([FromBody] CredentialsVM credentials)
        {
            var result = await _signInManager.PasswordSignInAsync(credentials.Email, credentials.Password, false, false);

            if (!result.Succeeded)
            {
                return(BadRequest(new ApiError {
                    Message = "Login failed."
                }));
            }

            var user = await _userManager.FindByEmailAsync(credentials.Email);

            if (user == null)
            {
                return(BadRequest(new ApiError {
                    Message = "Email not found."
                }));
            }

            TokenVM tokenVM = new TokenVM()
            {
                token      = TokenUtility.CreateToken(user),
                expires_at = DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeMilliseconds()
            };

            return(Ok(tokenVM));
        }
        public ActionResult LoginMobile(User user)
        {
            var failLogin = new
            {
                Rank = 99,
            };

            //fetch from database
            if (ModelState.IsValid)
            {
                User u = UserDao.GetUser(user);
                if (u == null)
                {
                    return(Json(failLogin, JsonRequestBehavior.AllowGet));
                }

                Debug.WriteLine(u.Department.DepartmentId);
                Debug.WriteLine(u.Department.DepartmentName);

                string token = TokenUtility.Encrypt(u);
                Response.Cookies["token"].Value   = token;
                Response.Cookies["token"].Expires = DateTime.Now.AddDays(1);

                var login = new
                {
                    Department = u.Department.DepartmentId,
                    UserId     = u.UserId,
                    Name       = u.Name,
                    Rank       = u.Rank,
                };
                return(Json(login, JsonRequestBehavior.AllowGet));
            }
            return(Json(failLogin, JsonRequestBehavior.AllowGet));
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var isAnonymousAllowed = context.ActionDescriptor.EndpointMetadata
                                     .Any(x => x.GetType() == typeof(AllowAnonymousAttribute));

            if (isAnonymousAllowed)
            {
                return;
            }

            var userLogin = context.HttpContext.GetLoginFromClaims();

            if (userLogin == null)
            {
                context.Result = new UnauthorizedObjectResult(
                    "Error: HttpContext.User.LoginClaim is null");
                return;
            }

            var isValidated = TokenUtility.Validate(userLogin,
                                                    context.HttpContext.Request.Headers);

            if (!isValidated)
            {
                context.Result = new UnauthorizedObjectResult(
                    "Error: Token is not valid!");
                return;
            }
        }
Example #10
0
        public IActionResult ResetPasswordRequest([FromBody] PasswordResetRequest model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Valid email address is required"));
            }

            ActionResponse response  = new ActionResponse();
            var            foundUser = userService.GetUserByEmail(model.Email);

            if (foundUser != null)
            {
                string adminEmail = HttpContext.RequestServices.GetRequiredService <IConfiguration>()
                                    .GetValue <String>("Email:Smtp:AdminEmail");
                string             resetPasswordUrl = configuration["ResetPasswordUrl"];
                DateTime           datedTime        = DateTime.Now;
                PasswordTokenModel tModel           = new PasswordTokenModel()
                {
                    Email     = foundUser.Email,
                    TokenDate = datedTime
                };

                TokenUtility            utility    = new TokenUtility();
                string                  token      = utility.GeneratePasswordResetToken(tModel);
                PasswordResetEmailModel resetModel = new PasswordResetEmailModel()
                {
                    Email = foundUser.Email,
                    Token = token,
                    Url   = resetPasswordUrl
                };

                response = userService.ResetPasswordRequest(resetModel, datedTime, adminEmail);
            }
            return(Ok(response));
        }
Example #11
0
        /// <summary>
        /// 添加或更新Token
        /// </summary>
        /// <param name="result"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private string RenewToken(ResultDTO result, Mc_User user)
        {
            string   secretKey = Guid.NewGuid().ToString();
            Mc_Token tokenInfo = DBUtility.CubeDb.From <Mc_Token>()
                                 .Where(Mc_Token._.User_Id == user.Id)
                                 .ToList()
                                 .FirstOrDefault();

            if (tokenInfo == null)
            {
                tokenInfo            = new Mc_Token();
                tokenInfo.User_Id    = user.Id;
                tokenInfo.Login_Time = DateTime.Now;
                tokenInfo.Secret_Key = secretKey;
                DBUtility.CubeDb.Insert <Mc_Token>(tokenInfo);
            }
            else
            {
                tokenInfo.Login_Time = DateTime.Now;
                tokenInfo.Secret_Key = secretKey;
                DBUtility.CubeDb.Update <Mc_Token>(tokenInfo);
            }
            result.success = true;
            TokenDTO token = new TokenDTO()
            {
                LoginName = user.Login_Name,
                LoginTime = tokenInfo.Login_Time,
                SecretKey = Guid.Parse(secretKey)
            };

            return(TokenUtility.GenerateToken(token));
        }
Example #12
0
        /// <summary>
        /// Produces the right visibility token for a node.
        /// </summary>
        /// <param name="tokenList">The <see cref="SyntaxTokenList"/> containing the list of modifiers.</param>
        /// <returns></returns>
        public static VisibilityToken Get(this SyntaxTokenList tokenList)
        {
            if (tokenList == null)
            {
                throw new ArgumentNullException("tokenList");
            }

            VisibilityToken visibility = VisibilityToken.None;

            foreach (SyntaxToken token in tokenList)
            {
                if (token.ValueText.CompareTo(TokenUtility.ToString(VisibilityToken.Public)) == 0)
                {
                    visibility = visibility | VisibilityToken.Public; continue;
                }
                if (token.ValueText.CompareTo(TokenUtility.ToString(VisibilityToken.Private)) == 0)
                {
                    visibility = visibility | VisibilityToken.Private; continue;
                }
                if (token.ValueText.CompareTo(TokenUtility.ToString(VisibilityToken.Internal)) == 0)
                {
                    visibility = visibility | VisibilityToken.Internal; continue;
                }
                if (token.ValueText.CompareTo(TokenUtility.ToString(VisibilityToken.Protected)) == 0)
                {
                    visibility = visibility | VisibilityToken.Protected; continue;
                }
                if (token.ValueText.CompareTo(TokenUtility.ToString(VisibilityToken.Static)) == 0)
                {
                    visibility = visibility | VisibilityToken.Static; continue;
                }
            }

            return(visibility);
        }
Example #13
0
        public SSOContext(string token)
        {
            TokenInfo = TokenUtility.GetTokenInfo(Token);
            string userId = DBUtility.CubeDb.From <Mc_Token>().Where(Mc_Token._.Secret_Key == TokenInfo.SecretKey)
                            .Select(Mc_Token._.All).ToList().FirstOrDefault().User_Id.ToString();

            User = DBUtility.CubeDb.From <Mc_User>().Where(Mc_User._.Id == userId).Select(Mc_User._.All).FirstDefault();
        }
Example #14
0
        void IAuthenticationFilter.OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.HttpContext.Request.Cookies["token"] != null)
            {
                string   token        = filterContext.HttpContext.Request.Cookies["token"].Value;
                string   decodedToken = TokenUtility.Decrypt(token);
                string[] arr          = decodedToken.Split(new string[] { "%" }, StringSplitOptions.None);
                int      departmentId = Convert.ToInt32(arr[2]);

                Department d = new Department()
                {
                    DepartmentId = departmentId
                };
                User user = new User()
                {
                    Department = d,
                    UserId     = Convert.ToInt32(arr[0])
                };

                User loggedInUser = UserDao.GetUserProfile(user);

                Debug.WriteLine("Auth Filter Department Id " + loggedInUser.Department.DepartmentId);

                if (loggedInUser != null)
                {
                    Controller controller = filterContext.Controller as Controller;
                    controller.ViewData["rank"] = loggedInUser.Rank;
                    filterContext.RouteData.Values.Add("userId", loggedInUser.UserId);
                    filterContext.RouteData.Values.Add("departmentId", loggedInUser.Department.DepartmentId);
                    filterContext.RouteData.Values.Add("rank", loggedInUser.Rank);
                    filterContext.Controller.ViewData["Username"] = loggedInUser.Name;
                }
                else
                {
                    HttpCookie cookie = new HttpCookie("token", "...");
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    filterContext.HttpContext.Response.Cookies.Add(cookie);

                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary
                    {
                        { "controller", "Auth" },
                        { "action", "Index" }
                    });
                }
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                {
                    { "controller", "Auth" },
                    { "action", "Index" }
                });
            }
        }
Example #15
0
        public ActionResult Login(User user)
        {
            //fetch from database
            if (ModelState.IsValid)
            {
                User u = UserDao.GetUser(user);
                if (u == null)
                {
                    ViewData["Error"] = "Username or Password is wrong.";
                    return(View());
                }

                string     token  = TokenUtility.Encrypt(u);
                HttpCookie cookie = new HttpCookie("token", token);
                cookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(cookie);

                RedirectToRouteResult result = null;
                switch (u.Rank)
                {
                case (int)UserRank.Manager:
                    result = RedirectToRoute("PendingOrders");
                    break;

                case (int)UserRank.Supervisor:
                    result = RedirectToRoute("PendingOrders");
                    break;

                case (int)UserRank.TemporaryHead:
                    result = RedirectToRoute("requestitems");
                    break;

                case (int)UserRank.Employee:
                    result = RedirectToRoute("requestitems");
                    break;

                case (int)UserRank.Head:
                    result = RedirectToRoute("pendingrequisitions");
                    break;

                case (int)UserRank.Clerk:
                    result = RedirectToRoute("orderitems");
                    break;
                }


                return(result);
            }

            return(View());
        }
Example #16
0
        public async Task <LoginResponseData> Login(LoginRequestData model, string ip)
        {
            if (_dbPatchMgr.GetStatus())
            {
                throw new ApplicationException("Database syncronization in progress, please try to login in few minutes...");
            }
            _dbPatchMgr.Sync();

            var refreshTokenLifeTime = ValidateClientAuthentication(model.ClientId, model.ClientSecret);
            var user = await _userRepo.FindUserByUsername(model.Username);

            if (user == null)
            {
                throw new ApplicationException("Invalid username or password");
            }
            if (await _userRepo.IsUserLogout(user))
            {
                throw new ApplicationException("User account is been logout");
            }
            if (!user.IsActive)
            {
                throw new ApplicationException("User account inactive");
            }
            if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Failed)
            {
                throw new ApplicationException("Invalid username or password");
            }
            var jwtSecurityToken = TokenUtility.GenerateJwtSecurityToken(_appConfig.GetSection("AppConfiguration"), TokenUtility.GenerateClaims(user.UserName, user.Id));
            var userVm           = UserExtension.BuildUserViewModel(user);
            var refreshToken     = TokenUtility.GenerateRefreshToken();

            await SaveRefreshToken(model.ClientId, model.Username, refreshToken, refreshTokenLifeTime, ip);

            user.LastLoginDate = DateTime.UtcNow;
            _userRepo.Update(user);
            var response = new LoginResponseData()
            {
                UserId            = userVm.UserID,
                Username          = userVm.Username,
                FullName          = userVm.FullName,
                ProfilePictureUrl = userVm.ProfilePictureUrl,
                Roles             = userVm.Roles,
                Token             = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                TokenExpires      = jwtSecurityToken.ValidTo,
                TokenIssued       = jwtSecurityToken.ValidFrom,
                RefreshToken      = refreshToken,
                Email             = userVm.Email
            };

            return(response);
        }
Example #17
0
        public IActionResult RequestToken(AuthRequest request)
        {
            //Kept it simple for demo purpose
            //var user = new OperadoresControlador().ObterNoTracking(P => P.OpMat == request.UserName && P.OpSenha == request.Password);
            //if (user == null) return BadRequest("Invalid credentials.");
            //var token = new TokenUtility().GenerateToken(user.OpMat, user.OpIdOp.ToString());
            var tok    = new TokenUtility().GenerateToken("user", "1");
            var result = Ok(new
            {
                token = tok
            });

            return(result);
        }
Example #18
0
 UserModel BuildUser(string provider, string field)
 {
     Dictionary<string, string> token = new Dictionary<string, string>();
     UserModel CurrentUser = new UserModel();
     if (HttpContext.Current.Request.Headers["Authorization"] != null)
     {
         string id_token = HttpContext.Current.Request.Headers.GetValues("Authorization").FirstOrDefault().Substring(7);
         token = TokenUtility.GenToken(id_token);
         DateTime expTime = new DateTime(1970, 1, 1)
             .AddSeconds(Convert.ToDouble(token["exp"]));
         Employee emp = TimeUnit.Employees.Get(x => x.Email == token[field]).FirstOrDefault();
         CurrentUser = TimeFactory.Create(emp, provider);
     }
     return CurrentUser;
 }
Example #19
0
        public IActionResult GetRandomKey()
        {
            //var randomKey = TokenUtility.GetRandomHexKey();
            Random random = new Random();

            int[] randomKeys = new int[8];
            for (int i = 0; i < 8; i++)
            {
                randomKeys[i] = random.Next(255);
            }

            var res = TokenUtility.Fix8ArrayToHex(randomKeys);

            return(Ok(new { RandomHexKey = res, RandomKeys = randomKeys }));
        }
Example #20
0
        public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary <string, object> htmlAttributes, bool generateToken)
        {
            var rc = helper.ViewContext.RequestContext;
            var routeCollection = helper.RouteCollection;

            if (generateToken)
            {
                var token = TokenUtility.GenerateUrlToken(controllerName, actionName, routeValues, TokenPassword);
                routeValues.Add("urltoken", token);
            }

            var link          = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes);
            var mvcHtmlString = MvcHtmlString.Create(link);

            return(mvcHtmlString);
        }
        public IActionResult RequestToken([FromBody] AuthRequest request)
        {
            //Kept it simple for demo purpose
            var user = _loginRepository.GetBy(request.UserName, request.Password);

            if (user == null)
            {
                return(BadRequest("Invalid credentials."));
            }
            var token = new TokenUtility().GenerateToken(user.UserName, user.Id.ToString());

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
Example #22
0
        public async Task <IActionResult> ResetPassword([FromBody] PasswordResetModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            TokenUtility utility   = new TokenUtility();
            var          tokenTime = utility.GetDecodedResetToken(model.Token);
            var          response  = await userService.ResetPasswordAsync(model, tokenTime);

            if (!response.Success)
            {
                return(BadRequest(response.Message));
            }
            return(Ok(response));
        }
Example #23
0
        public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, bool generateToken)
        {
            var rc = helper.ViewContext.RequestContext;
            var routeCollection = helper.RouteCollection;
            var rvd             = new RouteValueDictionary();

            if (generateToken)
            {
                var token = TokenUtility.GenerateUrlToken(controllerName, actionName, rvd, TokenPassword);
                rvd.Add("urltoken", token);
            }

            var link          = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, rvd, null);
            var mvcHtmlString = MvcHtmlString.Create(link);

            return(mvcHtmlString);
        }
Example #24
0
        public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, object routeValues, object htmlAttributes, bool generateToken)
        {
            var rc = helper.ViewContext.RequestContext;
            var routeCollection = helper.RouteCollection;
            var rvd             = new RouteValueDictionary(routeValues);

            if (generateToken)
            {
                var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword);
                rvd.Add("urltoken", token);
            }

            var attrib        = GetDictionaryFromObject(htmlAttributes);
            var link          = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, attrib);
            var mvcHtmlString = MvcHtmlString.Create(link);

            return(mvcHtmlString);
        }
Example #25
0
        public async Task <IActionResult> GetFitnessLogs(int userId)
        {
            var tokenInfo = TokenUtility.GetTokenInfo(HttpContext);

            if (userId != tokenInfo.Id)
            {
                return(Unauthorized(new { Error = "Invalid UserId" }));
            }

            try
            {
                var results = await _context.FitnessLogs
                              .AsNoTracking()
                              .Include("WorkoutType")
                              .Include("ExerciseMaps.Exercise.ExerciseType")
                              .Include("ExerciseMaps.Exercise.QuantityType")
                              .Where(log =>
                                     log.UserId == userId
                                     )
                              .ToListAsync();

                return(Ok(new { Data = results }));
            }
            catch (Exception ex)
            {
                var message = $"Error retrieving fitness logs for user {userId}";
                var data    = new
                {
                    Source         = ex.Source,
                    Message        = ex.Message,
                    InnerException = ex.InnerException,
                };

                var dataString = JsonConvert.SerializeObject(data);

                _context.Logs.Add(new KravWodLog {
                    Message = message, Data = dataString, TimeStamp = DateTimeOffset.Now
                });
                _context.SaveChanges();

                return(StatusCode(500, new { Error = message }));
            }
        }
Example #26
0
    public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, bool generateToken)
    {
        var rvd = new RouteValueDictionary();

        if (generateToken)
        {
            // Call the generateUrlToken method which create the hash
            var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, "@#123%#");

            // The hash is added to the route value dictionary
            rvd.Add("urltoken", token);
        }

        // the link is formed by using the GenerateLink method.
        var link          = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd);
        var mvcHtmlString = MvcHtmlString.Create(link);

        return(mvcHtmlString);
    }
Example #27
0
        public IActionResult Token([FromBody] AuthenticateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            SecurityHelper sHelper = new SecurityHelper();

            model.Password = sHelper.GetPasswordHash(model.Password);
            var foundUser = userService.AuthenticateUser(model.Email, model.Password);

            if (!string.IsNullOrEmpty(foundUser.Name))
            {
                TokenModel tModel = new TokenModel()
                {
                    Id                  = foundUser.Id.ToString(),
                    JwtKey              = configuration["JwtKey"],
                    JwtAudience         = configuration["JwtAudience"],
                    JwtIssuer           = configuration["JwtIssuer"],
                    TokenExpirationDays = configuration["JwtExpireDays"],
                    OrganizationId      = foundUser.OrganizationId.ToString(),
                    UserType            = Convert.ToInt32(foundUser.UserType),
                    Email               = foundUser.Email
                };
                TokenUtility   tManager = new TokenUtility();
                var            jwtToken = tManager.GenerateToken(tModel);
                UserReturnView uView    = new UserReturnView()
                {
                    Token    = jwtToken,
                    Name     = foundUser.Name,
                    UserType = foundUser.UserType
                };
                return(Ok(uView));
            }
            ErrorModel errModel = new ErrorModel()
            {
                Error = "Username/Password provided is invalid"
            };

            return(Ok(errModel));
        }
Example #28
0
        /// <summary>
        /// This is the extended method of Html.ActionLink.This class has the extended methods for the 10 overloads of this method
        /// All the overloaded method applys the same logic excepts the parameters passed in
        /// </summary>
        /// <param name="helper">The helper.</param>
        /// <param name="linkText">The link text.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="generateToken">if set to <c>true</c> [generate token].</param>
        /// <returns></returns>
        public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, bool generateToken)
        {
            var rc = helper.ViewContext.RequestContext;
            var routeCollection = helper.RouteCollection;
            var rvd             = new RouteValueDictionary();

            if (generateToken)
            {
                // Call the generateUrlToken method which create the hash
                var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword);

                // The hash is added to the route value dictionary
                rvd.Add("urltoken", token);
            }

            // the link is formed by using the GenerateLink method.
            var link          = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, null);
            var mvcHtmlString = MvcHtmlString.Create(link);

            return(mvcHtmlString);
        }
Example #29
0
        public async Task <ActionResult <LoginResponse> > Login(LoginRequest request)
        {
            var loginResult = await _signInManager
                              .PasswordSignInAsync(request.UserName, request.Password, false, false);

            if (loginResult.Succeeded)
            {
                var userData = await _userRepository.FindUserByUserName(request.UserName);

                var roles = await _userRepository.GetAllUserRoles(userData);

                userData.RefreshToken = TokenUtility.GenerateRefreshToken();
                await _userRepository.Update(userData);

                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, request.UserName)
                };

                roles.ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

                var token = TokenUtility.GenerateToken(claims);

                var response = new LoginResponse
                {
                    Token          = token,
                    RefreshToken   = userData.RefreshToken,
                    ExpirationDate = DateTime.Now.AddMinutes(60).ToString("g")
                };

                return(Ok(response));
            }

            return(Unauthorized());
        }
Example #30
0
 public bool ValidateToken()
 {
     return(TokenUtility.ValidToken(SSOContext.Token));
 }