Exemplo n.º 1
0
        public IActionResult Login(LoginDTO login)
        {
            var wasLoginSuccessful = _userRepository.Login(login.Username, login.Password);

            if (wasLoginSuccessful == null)
            {
                return(Forbid());
            }
            var jwtHelper   = new JwtHelper();
            var newJwtToken = jwtHelper.GenerateToken(new List <Claim> {
                new Claim(ClaimTypes.Name, login.Username), new Claim("userId", $"{wasLoginSuccessful.Value}")
            });
            var newRefreshToken = jwtHelper.GenerateRefreshToken();

            _userRepository.SaveRefreshToken(wasLoginSuccessful.Value, newRefreshToken);
            return(Ok(new ObjectResult(new
            {
                token = newJwtToken,
                refreshToken = newRefreshToken,
                userId = wasLoginSuccessful.Value
            })));
        }
        public async Task Invoke(HttpContext context)
        {
            var token  = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            int?userId = 0;

            if (token != null)
            {
                var tokenHelper = new JwtHelper(_conf);

                userId = tokenHelper.ValidateJwtToken(token);

                // si no es valido se setea en 0 para validar en los endpoints
                if (userId == null)
                {
                    userId = 0;
                }
            }

            context.Items["UserId"] = userId;

            await _next(context);
        }
Exemplo n.º 3
0
 public IEnumerable <sp_project_course_detail_v3_Result> detail(projectCourseModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_project_course_detail_v3_Result> result = context.sp_project_course_detail_v3(value.id).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 4
0
 public Task Invoke(HttpContext httpContext)
 {
     if (GetNeedOrNeedNotFlag.GetFlag(httpContext))
     {
         HttpRequest request = httpContext.Request;
         if (!request.Headers.TryGetValue("X-Token", out var apiKeyHeaderValues))
         {
             httpContext.Response.ContentType = "application/json";
             httpContext.Response.StatusCode  = StatusCodes.Status401Unauthorized;
             var a = new
             {
                 success = false,
                 msg     = "此请求未包含JWT令牌,禁止访问!!",
                 cause   = "此请求未包含JWT令牌,禁止访问!"
             };
             httpContext.Response.WriteAsync(JsonConvert.SerializeObject(a));
             return(Task.FromResult(0));
         }
         else
         {
             JwtHelper helper = new JwtHelper();
             request.EnableBuffering();//可以多次多次读取http内包含的数据
             if (!helper.ValidateJwt(apiKeyHeaderValues.ToString(), out string Msg))
             {
                 httpContext.Response.ContentType = "application/json";
                 httpContext.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                 var a = new
                 {
                     success = false,
                     msg     = Msg,
                     cause   = Msg
                 };
                 httpContext.Response.WriteAsync(JsonConvert.SerializeObject(a));
                 return(Task.FromResult(0));
             }
         }
     }
     return(_next(httpContext));
 }
Exemplo n.º 5
0
        public async Task <ActionResult <string> > Register([FromBody] RegisterRequest model)
        {
            var appUser = new AppUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await _userManager.CreateAsync(appUser, model.Password);

            if (result.Succeeded)
            {
                _logger.LogInformation("New user created.");
                var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(appUser);

                var jwt = JwtHelper.GenerateJwt(
                    claimsPrincipal.Claims,
                    _configuration["JWT:Key"],
                    _configuration["JWT:Issuer"],
                    int.Parse(_configuration["JWT:ExpireDays"]));
                _logger.LogInformation("Token generated for user");
                return(Ok(new { token = jwt }));
            }
            return(StatusCode(406));
        }
Exemplo n.º 6
0
 public IEnumerable <sp_worklist_Result> searchWorkList(dashBoardModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context             = new StandardCanEntities();
         IEnumerable <sp_worklist_Result> result = context.sp_worklist(userId, value.draft, value.pending, value.watiDP, value.approve, value.cancel).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 7
0
 public IEnumerable <sp_bookroom_search_v3_Result> search_all_calendar(bookRoomModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_bookroom_search_v3_Result> result = context.sp_bookroom_search_v3(value.room_from, value.room_to, value.date_from, value.date_to, value.status_from, value.status_to, "all").AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 8
0
        public ActionResult <ResponseModel> PostLogin(LoginUserModel loginUser)
        {
            ResponseModel responseModel = null;

            try
            {
                string userName  = loginUser.userName;
                var    authModel = _authService.Autheticate(loginUser.userName, loginUser.password);

                if (authModel != null)
                {
                    var ContactId = authModel.ContactId.ToGuid();
                    var unit      = _faciTechDbContext.UnitContact
                                    .Include(e => e.Unit)
                                    .Where(e => e.ContactId == ContactId)
                                    .Select(e => e.Unit)
                                    .FirstOrDefault();
                    Guid communityId = Guid.Empty;
                    Guid unitId      = Guid.Empty;
                    if (unit != null)
                    {
                        communityId = unit.CommunityId;
                        unitId      = unit.Id;
                    }
                    //Token to be sent back to Client
                    string token = JwtHelper.CreateToken(authModel, communityId, unitId, _configuration.GetJwtTokenKey());
                    responseModel = new ResponseModel(ResponseStatus.Success, "", new { auth = authModel, token = token });
                }
                else
                {
                    responseModel = new ResponseModel(ResponseStatus.Error, "Invalid Username or Password");
                }
            }
            catch (Exception ex)
            {
                responseModel = new ResponseModel(ResponseStatus.Error, "Unknow error while autheticating");
            }
            return(responseModel);
        }
Exemplo n.º 9
0
        public async Task <ActionResult> ChangeImage(HttpPostedFileBase file)
        {
            if (file == null || file.ContentLength == 0)
            {
                return(Json(new { status = "fail", result = "图片不可为空,请重试!" }, JsonRequestBehavior.AllowGet));
            }
            IUserManager userManager = new UserManager();
            //获取当前登陆的id,cookie的id需要解密
            string userCookieId = ""; string message;

            if (Request.Cookies["userId"] != null)
            {
                if (!JwtHelper.GetJwtDecode(Request.Cookies["userId"].Value, out userCookieId, out message))
                {
                    return(Json(new { status = "fail", result = message }, JsonRequestBehavior.AllowGet));
                }
            }
            string userId = Session["userId"] == null ? userCookieId : Session["userId"].ToString();//优先获取session的id

            if (userId == null || userId.Trim() == "")
            {
                return(Json(new { status = "fail", result = "获取用户信息失败,请检查登陆状态" }, JsonRequestBehavior.AllowGet));
            }
            UserInformationDto user = await userManager.GetUserById(Guid.Parse(userId));

            if (user.ImagePath != null && user.ImagePath != "default.png")//存在图片路径则删除就图片
            {
                string savepath    = Server.MapPath("../Image");
                string oldFileName = Path.Combine(savepath, user.ImagePath);
                System.IO.File.Delete(oldFileName);
            }
            string newFileName = ProcessUploadedFile(file);

            if (!await userManager.ChangeUserImage(Guid.Parse(userId), newFileName))
            {
                return(Json(new { status = "fail", result = "修改失败" }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new { status = "ok", path = newFileName }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 10
0
        public projectMasterModel master(projectModel value)
        {
            projectMasterModel result = new projectMasterModel();

            try
            {
                using (var context = new StandardCanEntities())
                {
                    if (String.IsNullOrEmpty(value.user_id))
                    {
                        throw new Exception("Unauthorized Access");
                    }
                    var userId = JwtHelper.GetUserIdFromToken(value.user_id);
                    if (String.IsNullOrEmpty(userId))
                    {
                        throw new Exception("Unauthorized Access");
                    }

                    string sql = "select convert(nvarchar(4), MPJ_YEAR) code, convert(nvarchar(4), MPJ_YEAR) [text] ";
                    sql        += " from MAS_PROJECT ";
                    sql        += " where MPJ_YEAR is not null ";
                    sql        += " group by    MPJ_YEAR ";
                    result.year = context.Database.SqlQuery <dropdown>(sql).ToList();

                    sql            = "select		convert(nvarchar(5), MPJ_ID) code ";
                    sql           += " , MPJ_NAME [text] ";
                    sql           += " from MAS_PROJECT ";
                    sql           += " where MPJ_STATUS = 1 ";
                    sql           += " order by MPJ_NAME ";
                    result.project = context.Database.SqlQuery <dropdown>(sql).ToList();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(result);
        }
Exemplo n.º 11
0
        private void OnGameStateUpdate(UpdatedGameStateMessage msg, DateTime timestamp)
        {
            if (!this.GameHosts.ContainsKey(msg.GameId))
            {
                throw new Exception("This game id doesn't match any active game");
            }

            var game      = this.GameHosts[msg.GameId];
            var userToken = JwtHelper.DecodeToken(msg.UserToken);

            if (userToken == null || game.Spectators.ContainsKey(userToken.UserId) || !game.Players.ContainsKey(userToken.UserId))
            {
                throw new Exception("This user is not allowed to change the map state");
            }

            // Update the current map state
            var stats = game.Map.UpdateScene(msg.UpdatedSceneObjects, userToken.UserId, timestamp);

            game.GameStatisticsUpdates.Add(stats);

            this.BroadcastGameState(game);
        }
Exemplo n.º 12
0
        public async Task <ActionResult> AddComment(CreateCommentViewModel model)
        {
            string userid = ""; string message;

            if (Request.Cookies["userId"] != null)
            {
                if (!JwtHelper.GetJwtDecode(Request.Cookies["userId"].Value, out userid, out message))
                {
                    return(Json(new { result = message, status = "fail" }));
                }
            }
            string userId = Session["userId"] == null ? userid : Session["userId"].ToString();

            if (userId == "")
            {
                return(Json(new { result = "尚未登陆无法操作!", status = "fail" }));
            }
            IArticleManager articleManager = new ArticleManager();
            await articleManager.CreateComment(model.Id, Guid.Parse(userId), model.Content);

            return(Json(new { status = "ok" }));
        }
Exemplo n.º 13
0
        public async Task <ActionResult> GetLikeHate(Guid id)
        {
            string userid = ""; string message;

            if (Request.Cookies["userId"] != null)
            {
                if (!JwtHelper.GetJwtDecode(Request.Cookies["userId"].Value, out userid, out message))
                {
                    return(Json(new { result = message, status = "fail" }));
                }
            }
            string userId = Session["userId"] == null ? userid : Session["userId"].ToString();

            if (userId == "")
            {
                return(Json(new { result = "尚未登陆无法操作!", status = "fail" }, JsonRequestBehavior.AllowGet));
            }
            IArticleManager articleManager = new ArticleManager();
            string          result         = await articleManager.GetLikeHate(id, Guid.Parse(userId));

            return(Json(new { status = "ok", result }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 14
0
        public async Task <AuthResponseVM> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var response = new AuthResponseVM();

            var user = await userManager.FindByEmailAsync(request.Email);

            var result = await userManager.CheckPasswordAsync(user, request.Password);

            if (!result)
            {
                response.Errors = new List <string> {
                    "Wrong Credentials"
                };
                return(response);
            }
            var token = await JwtHelper.GenerateToken(user, jwtSettings.Secret, userManager);

            response.Email = user.Email;
            response.Token = token;

            return(response);
        }
Exemplo n.º 15
0
        public ActionResult <string> Login(Object PostData)
        {
            JObject JsonData = JObject.FromObject(PostData);
            string  username = JsonData["UserName"] == null ? "" : JsonData["UserName"].ToString();
            string  password = JsonData["password"] == null ? "" : JsonData["password"].ToString();
            Dictionary <string, string> results3 = JsonConvert.DeserializeObject <Dictionary <string, string> >(PostData.ToString());

            Model.ErrorMsg = "";
            JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();

            password = CommonHelp.GetMD5(password);
            JH_Auth_User        userInfo = new JH_Auth_User();
            List <JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => (d.UserName == username || d.mobphone == username) && d.UserPass == password).ToList();

            if (userList.Count() == 0)
            {
                Model.ErrorMsg = "用户名或密码不正确";
            }
            else
            {
                userInfo = userList[0];
                if (userInfo.IsUse != "Y")
                {
                    Model.ErrorMsg = "用户被禁用,请联系管理员";
                }
                if (Model.ErrorMsg == "")
                {
                    Model.Result  = JwtHelper.CreateJWT(username, "Admin");
                    Model.Result1 = userInfo.UserName;
                    Model.Result2 = qyModel.FileServerUrl;
                    Model.Result4 = userInfo;

                    CacheHelp.Remove(userInfo.UserName);
                }
            }


            return(ControHelp.CovJson(Model));;
        }
Exemplo n.º 16
0
        public dynamic GetJwtStr(string loginName, string passWord)
        {
            string jwtStr = string.Empty;
            bool   status = false;

            if (loginName == "Admin")
            {
                TokenModelJwt tokenModel = new TokenModelJwt()
                {
                    Uid  = 1,
                    Role = "Admin",
                    Work = "管理员"
                };
                jwtStr = JwtHelper.GetJwtToken(tokenModel);
                status = true;
            }
            else
            {
                jwtStr = "验证失败!";
            }
            return(Ok(new { success = status, data = jwtStr }));
        }
Exemplo n.º 17
0
        public async Task <ApiResult> Info()
        {
            string  parm   = doMain;
            User    user   = JwtHelper.JwtDecrypt <User>(ControllerContext);
            UserDTO result = await userService.GetModelAsync(user.Id);

            UserCenterInfoApiModel model = new UserCenterInfoApiModel();

            model.amount       = result.Amount;
            model.frozenAmount = result.FrozenAmount;
            model.bonusAmount  = result.BonusAmount + result.FrozenAmount;
            model.buyAmount    = result.BuyAmount + (await userService.GetTeamBuyAmountAsync(user.Id));
            model.createTime   = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
            if (!string.IsNullOrEmpty(result.HeadPic))
            {
                if (result.HeadPic.Contains("https:"))
                {
                    model.headPic = result.HeadPic;
                }
                else
                {
                    model.headPic = parm + result.HeadPic;
                }
            }
            else
            {
                model.headPic = parm;
            }
            model.id          = result.Id;
            model.levelId     = result.LevelId;
            model.levelName   = result.LevelName;
            model.mobile      = result.Mobile;
            model.nickName    = result.NickName;
            model.recommonder = result.RecommendCode;
            model.userCode    = result.UserCode;
            return(new ApiResult {
                status = 1, data = model
            });
        }
Exemplo n.º 18
0
        public async Task <IActionResult> UpdatePermissionClaims(int userId, int environmentId)
        {
            if (!this.VerifyUser(userId))
            {
                return(Unauthorized());
            }

            Permission permissions = await _authRepo.GetUserPermissionForEnvironment(userId, environmentId);

            if (permissions == null)
            {
                return(Unauthorized());
            }

            var    newClaims   = BuildPermissionClaims(permissions);
            string newJwtToken = JwtHelper.CreateToken(newClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(_tokenLifeTimeSeconds));

            return(new ObjectResult(new
            {
                permissionsToken = newJwtToken,
            }));
        }
Exemplo n.º 19
0
        public async Task <ResponseModel> RefreshToken(string token = "")
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(token))
            {
                _ResponseModel.Code    = ResponseCode.Error;
                _ResponseModel.Message = MessageModel.InvalidToken;
                return(_ResponseModel);
            }
            var oldTokenModel = JwtHelper.SerializeJwt(token);

            if (oldTokenModel != null)
            {
                var user = await _loginServices.GetUser(oldTokenModel.Uid.ToString());

                if (user != null)
                {
                    JwtTokenModel tokenModel = new JwtTokenModel();
                    tokenModel.Uid      = user.UserId;
                    tokenModel.Name     = user.UserName;
                    tokenModel.Role     = user.RoleIds;
                    _ResponseModel.Data = JwtHelper.IssueJwt(tokenModel);
                    return(_ResponseModel);
                }
                else
                {
                    _ResponseModel.Code    = ResponseCode.Error;
                    _ResponseModel.Message = MessageModel.InvalidToken;
                    return(_ResponseModel);
                }
            }
            else
            {
                _ResponseModel.Code    = ResponseCode.Error;
                _ResponseModel.Message = MessageModel.InvalidToken;
                return(_ResponseModel);
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> DeleteComment(int commentId)
        {
            try
            {
                var token = Request.Headers["Authorization"].ToString();

                var deletedEntry = await CommentService.GetByIdAsync <Comment>(commentId);

                if (deletedEntry == null)
                {
                    return(NotFound());
                }
                if (JwtHelper.CheckIfUserIsMember(token) && deletedEntry.PublishedById != JwtHelper.GetUserIdFromJwt(token))
                {
                    return(Forbid());
                }
                if (JwtHelper.CheckIfUserIsModerator(token))
                {
                    var news = await NewsService.GetByIdAsync <News>(deletedEntry.NewsId);

                    if (news.PublishedById != JwtHelper.GetUserIdFromJwt(token))
                    {
                        return(Forbid());
                    }
                }

                await CommentService.Delete <Comment>(commentId);

                return(Ok(new Response {
                    Status = ResponseType.Successful
                }));
            }
            catch
            {
                return(Ok(new Response {
                    Status = ResponseType.Failed
                }));
            }
        }
Exemplo n.º 21
0
        public async Task <ApiResult> Add(AddressAddModel model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                return(new ApiResult {
                    status = 0, msg = "收货人姓名不能为空"
                });
            }
            if (string.IsNullOrEmpty(model.Mobile))
            {
                return(new ApiResult {
                    status = 0, msg = "收货人手机号不能为空"
                });
            }
            if (!Regex.IsMatch(model.Mobile, @"^1\d{10}$"))
            {
                return(new ApiResult {
                    status = 0, msg = "收货人手机号格式不正确"
                });
            }
            if (string.IsNullOrEmpty(model.Address))
            {
                return(new ApiResult {
                    status = 0, msg = "收货人地址不能为空"
                });
            }
            User user = JwtHelper.JwtDecrypt <User>(ControllerContext);
            long id   = await addressService.AddAsync(user.Id, model.Name, model.Mobile, model.Address, model.IsDefault);

            if (id <= 0)
            {
                return(new ApiResult {
                    status = 1, msg = "收货地址添加失败"
                });
            }
            return(new ApiResult {
                status = 1, msg = "收货地址添加成功"
            });
        }
Exemplo n.º 22
0
        public ActionResult GetJwtStr(string name, string pass)
        {
            string jwtStr;
            bool   suc;

            // 获取用户的角色名,请暂时忽略其内部是如何获取的,可以直接用 var userRole="Admin"; 来代替更好理解。
            //var userRole = await _sysUserInfoServices.GetUserRoleNameStr(name, pass);
            if (true)
            {
                // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。
                JwtTokenModel tokenModel = new JwtTokenModel {
                    Uid = 1, Role = "Admin"
                };
                jwtStr = JwtHelper.IssueJwt(tokenModel);//登录,获取到一定规则的 Token 令牌
                suc    = true;
            }
            return(Ok(new
            {
                success = suc,
                token = jwtStr
            }));
        }
        public ResponseMessageResult Get()
        {
            JwtModel jwtmodel    = JwtHelper.getToken(HttpContext.Current.Request.Headers.GetValues("Authorization").First().ToString());
            var      sy_merchant = from a in db.sy_merchant
                                   select new {
                id = a.id.ToString(),
                a.name,
            };

            if (sy_merchant == null)
            {
                model.message     = "暂无数据";
                model.status_code = 200;
            }
            else
            {
                model.data        = sy_merchant.ToList();
                model.message     = "查询成功";
                model.status_code = 200;
            }
            return(new ResponseMessageResult(Request.CreateResponse((HttpStatusCode)model.status_code, model)));
        }
Exemplo n.º 24
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //base.OnAuthorization(filterContext);
            //当有AllowAnonymous特性时跳过
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }
            //当cookie数据不为空,session数据为空时。同步cookie的数据到session中
            if (filterContext.HttpContext.Session["userId"] == null && filterContext.HttpContext.Request.Cookies["userId"] != null)
            {
                filterContext.HttpContext.Session["loginName"] = filterContext.HttpContext.Request.Cookies["loginName"].Value;
                string userId; string message;
                JwtHelper.GetJwtDecode(filterContext.HttpContext.Request.Cookies["userId"].Value, out userId, out message);//验证id是否被篡改
                filterContext.HttpContext.Session["userId"] = userId;
            }


            if (!(filterContext.HttpContext.Session["userId"] != null || filterContext.HttpContext.Request.Cookies["userId"] != null))//找不到session或cookie跳转未登录
            {
                //filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
                //{
                //    { "controller","Home"},{ "action","Login"}
                //});
                //没有登陆的情况下跳转登陆界面会带有returnUrl
                //string localPath = filterContext.HttpContext.Request.Url.LocalPath;//本地路径
                //if (localPath.Contains("ArticleList"))//包含列表的添加id参数
                //{
                //    partPath = filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.LocalPath) + "?userId=" + filterContext.HttpContext.Session["userId"];
                //}
                //else
                //{
                //    partPath = filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.LocalPath);
                //}
                string partPath = filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString());//部分路径
                filterContext.Result = new RedirectResult(string.Concat("/Home/Login?returnUrl=", partPath));
            }
        }
Exemplo n.º 25
0
 public IEnumerable <sp_formular_search_v2_Result> search(projectFormularModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_formular_search_v2_Result> result = context.sp_formular_search_v2(value.fml_type, value.fml_name).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 26
0
 public IEnumerable <sp_mb_get_schedule_Result> getSchedule(holidayModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_mb_get_schedule_Result> result = context.sp_mb_get_schedule(value.user_id).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 27
0
 public IEnumerable <sp_project_course_search_v2_Result> search(projectCourseModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_project_course_search_v2_Result> result = context.sp_project_course_search_v2(value.year_from, value.year_to, value.project_from, value.project_to, value.course_name, value.status_id).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 28
0
        public ActionResult <string> ExeAction(string Action, Object PostData)
        {
            Model.Action = Action;
            var           context     = _accessor.HttpContext;
            var           tokenHeader = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            TokenModelJWT tokenModel  = JwtHelper.SerializeJWT(tokenHeader);

            if (new DateTimeOffset(DateTime.Now.AddMinutes(5)).ToUnixTimeSeconds() > tokenModel.Exp)
            {
                //需要更新Token
                Model.uptoken = JwtHelper.CreateJWT(tokenModel.UserName, "Admin");
            }
            JH_Auth_UserB.UserInfo UserInfo = CacheHelp.Get(tokenModel.UserName) as JH_Auth_UserB.UserInfo;
            if (UserInfo == null)
            {
                UserInfo = new JH_Auth_UserB().GetUserInfo(10334, tokenModel.UserName);
                CacheHelp.Set(tokenModel.UserName, UserInfo);
            }
            try
            {
                JObject JsonData = JObject.FromObject(PostData);
                string  P1       = JsonData["P1"] == null ? "" : JsonData["P1"].ToString();
                string  P2       = JsonData["P2"] == null ? "" : JsonData["P2"].ToString();

                //Dictionary<string, string> results3 = JsonConvert.DeserializeObject<Dictionary<string, string>>(PostData.ToString());
                var function = Activator.CreateInstance(typeof(AuthManage)) as AuthManage;
                var method   = function.GetType().GetMethod(Action.ToUpper());
                method.Invoke(function, new object[] { JsonData, Model, P1, P2, UserInfo });
                new JH_Auth_LogB().InsertLog(Model.Action, "--调用接口", "", UserInfo.User.UserName, UserInfo.User.UserRealName, UserInfo.QYinfo.ComId, "");
            }
            catch (Exception ex)
            {
                Model.ErrorMsg = Action + "接口调用失败,请检查日志";
                Model.Result   = ex.ToString();
                new JH_Auth_LogB().InsertLog(Action, Model.ErrorMsg + ex.StackTrace.ToString(), ex.ToString(), tokenModel.UserName, "", 0, "");
            }

            return(ControHelp.CovJson(Model));
        }
Exemplo n.º 29
0
 public IEnumerable <sp_emp_search_byid_Result> search_byid(employeeModel value)
 {
     try
     {
         if (String.IsNullOrEmpty(value.user_id))
         {
             throw new Exception("Unauthorized Access");
         }
         var userId = JwtHelper.GetUserIdFromToken(value.user_id);
         if (String.IsNullOrEmpty(userId))
         {
             throw new Exception("Unauthorized Access");
         }
         StandardCanEntities context = new StandardCanEntities();
         IEnumerable <sp_emp_search_byid_Result> result = context.sp_emp_search_byid(value.emp_code).AsEnumerable();
         return(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 30
0
        public void JWT_Check_InvalidIssuedDate()
        {
            //Token generated using:
            //
            // scope = JwtScopes.Write
            // orgCode = ORG1
            // roleProfileId = fakeRoleId
            // asid = 20000000017
            // endpoint = https://nrls.com/fhir/documentreference
            // tokenOrigin = https://demonstrator.com
            // tokenStart = 2018-04-01T10:00:30+00:00

            var issued = new DateTime(2018, 4, 1, 10, 5, 30, DateTimeKind.Utc);

            var token = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2RlbW9uc3RyYXRvci5jb20iLCJzdWIiOiJodHRwczovL2ZoaXIubmhzLnVrL0lkL3Nkcy1yb2xlLXByb2ZpbGUtaWR8ZmFrZVJvbGVJZCIsImF1ZCI6Imh0dHBzOi8vbnJscy5jb20vZmhpci9kb2N1bWVudHJlZmVyZW5jZSIsImV4cCI6MTUyMjU3NzEzMCwiaWF0IjoxNTIyNTc2ODMwLCJyZWFzb25fZm9yX3JlcXVlc3QiOiJkaXJlY3RjYXJlIiwic2NvcGUiOiJwYXRpZW50L0RvY3VtZW50UmVmZXJlbmNlLndyaXRlIiwicmVxdWVzdGluZ19zeXN0ZW0iOiJodHRwczovL2ZoaXIubmhzLnVrL0lkL2FjY3JlZGl0ZWQtc3lzdGVtfDIwMDAwMDAwMDE3IiwicmVxdWVzdGluZ19vcmdhbml6YXRpb24iOiJodHRwczovL2ZoaXIubmhzLnVrL0lkL29kcy1vcmdhbml6YXRpb24tY29kZXxPUkcxIiwicmVxdWVzdGluZ191c2VyIjoiaHR0cHM6Ly9maGlyLm5ocy51ay9JZC9zZHMtcm9sZS1wcm9maWxlLWlkfGZha2VSb2xlSWQifQ.";

            var jwtHelper = new JwtHelper(_sdsService);

            var actual = jwtHelper.IsValid(token, JwtScopes.Read, issued);

            Assert.False(actual.Success);
        }