コード例 #1
0
        public async Task <IActionResult> PostImenuRole([FromBody] IMenuRole iMenuRole)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.IMenuRole.Add(iMenuRole);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ImenuRoleExists(iMenuRole.MenuId, iMenuRole.RoleId))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetImenuRole", new { id = iMenuRole.MenuId }, iMenuRole));
        }
コード例 #2
0
        public async Task <IActionResult> PutRoleGroup([FromRoute] int id, [FromBody] RoleGroup roleGroup)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != roleGroup.RoleId)
            {
                return(BadRequest());
            }

            _context.Entry(roleGroup).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoleGroupExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #3
0
        public async Task <IActionResult> PutMember([FromRoute] string id, [FromBody] Member member)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != member.Account)
            {
                return(BadRequest());
            }

            Member Origin = _context.Member.Single(x => x.Account == id);

            _context.Entry(member).State = EntityState.Modified;

            try
            {
                //防止新增時間被更動
                member.AddTime = Origin.AddTime;

                //刷新修改時間
                member.UpdatedTime = DateTime.Now;

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MemberExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #4
0
        public async Task <IActionResult> GetReflection()
        {
            var DbExistCtrls   = _context.Ctrl;
            var DbExistActions = _context.Actions;

            IEnumerable <Type> controllers = Assembly.GetExecutingAssembly().GetExportedTypes().Where(t => typeof(ControllerBase).IsAssignableFrom(t)).Select(t => t);

            foreach (Type controller in controllers)
            {
                int    ControllerID;
                string ControllerName = controller.Name.Replace("Controller", "");

                //檢查是否已有Controller登入
                if (IsControllerExists(ControllerName))
                {
                    //有則抓出id
                    ControllerID = DbExistCtrls.Where(x => x.Name == ControllerName).Select(x => x.CtrlId).SingleOrDefault();
                }
                else
                {
                    ControllerID = DbExistCtrls.Max(x => x.CtrlId) + 1;
                    Ctrl ctrl = new Ctrl()
                    {
                        CtrlId = ControllerID,
                        Name   = ControllerName
                    };

                    _context.Ctrl.Add(ctrl);
                    //先存擋
                    await _context.SaveChangesAsync();
                }

                List <MethodInfo> actions = controller.GetMethods().Where(t => !t.IsSpecialName && t.DeclaringType.IsSubclassOf(typeof(ControllerBase)) && t.DeclaringType.FullName == controller.FullName && t.IsPublic && !t.IsStatic).ToList();

                foreach (MethodInfo action in actions)
                {
                    Attribute attribute = action.GetCustomAttributes().Where(attr => attr is IActionHttpMethodProvider).FirstOrDefault();

                    string ActionName = action.Name;
                    string HttpMethod = attribute.GetType().Name.Replace("Http", "").Replace("Attribute", "");

                    //int ActionID;

                    //檢查是否已有Action登入在此Controller下
                    if (IsActionsExists(ActionName, ControllerID, HttpMethod))
                    {
                        // do nothing
                    }
                    else
                    {
                        int     ActID = DbExistActions.Max(x => x.ActionId) + 1;
                        Actions act   = new Actions()
                        {
                            ActionId     = ActID,
                            Name         = ActionName,
                            Method       = HttpMethod,
                            ControllerId = ControllerID
                        };
                        _context.Actions.Add(act);
                        await _context.SaveChangesAsync();
                    }
                }
            }

            return(Ok());
        }
コード例 #5
0
ファイル: AuthController.cs プロジェクト: TzyHuan/SystemAuth
        public async Task <IActionResult> Authenticate([FromBody] AuthRequest AuthRequest) //, string Account, string Password
        {
            bool HasUser  = _context.FindUser(AuthRequest.Account, AuthRequest.Password);
            bool HasToken = _context.FindToken(AuthRequest.Account);

            if (HasUser)
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_config["Jwt:Key"]);
                var authTime     = DateTime.UtcNow.ToLocalTime();//ToLocalTime變UTC+8時區
                var expiresAt    = authTime.AddDays(7);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(JwtClaimTypes.Audience, _config["Jwt:Audience"]),
                        new Claim(JwtClaimTypes.Issuer, _config["Jwt:Issuer"]),
                        new Claim(JwtClaimTypes.Id, AuthRequest.Account),
                        //new Claim(JwtClaimTypes.RoleId, RoleID.ToString()), //停止在jwt加入角色資訊,統一用id(帳號)判斷
                        //new Claim(JwtClaimTypes.Email, user.Email),
                        //new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber)
                    }),
                    Expires            = expiresAt,
                    NotBefore          = authTime,
                    IssuedAt           = authTime,
                    SigningCredentials = new SigningCredentials
                                         (
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha256Signature
                                         )
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                try
                {
                    Token SaveInfo = new Token
                    {
                        Account     = AuthRequest.Account,
                        TokenCode   = tokenString,
                        AuthTime    = authTime,
                        ExpiredTime = expiresAt,
                        Ip          = _accessor.HttpContext.Connection.RemoteIpAddress.ToString()
                    };
                    //將Token資訊加入Database
                    if (HasToken)
                    {
                        //若過去已有建立過Token,刷新資料
                        Token existInfo = _context.Token.Where(x => x.Account == AuthRequest.Account).FirstOrDefault();
                        _context.Entry(existInfo).State = EntityState.Modified;
                        _context.Entry(existInfo).CurrentValues.SetValues(SaveInfo);
                    }
                    else
                    {
                        _context.Token.Add(SaveInfo);
                    }

                    await _context.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    return(BadRequest("Could not create token \n" + ex));
                }

                return(Ok(new
                {
                    access_token = tokenString,
                    token_type = "Bearer",
                    profile = new
                    {
                        //sid = user.Id,
                        //name = user.Name,
                        auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                        expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                    }
                }));
            }
            else
            {
                //紀錄System Log
                _context.SystemLog.Add(new SystemLog
                {
                    LogTime = DateTime.Now,
                    Account = AuthRequest.Account,
                    Action  = ControllerContext.ActionDescriptor.ActionName,
                    Detail  = "Failure to authorize ",
                    Ip      = _accessor.HttpContext.Connection.RemoteIpAddress.ToString()
                });
                await _context.SaveChangesAsync();

                return(Unauthorized());
            }
        }