Esempio n. 1
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());
        }
Esempio n. 2
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());
        }
Esempio n. 3
0
        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());
            }
        }