Пример #1
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            IDbContext dbContext     = (IDbContext)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IDbContext));
            TimeSpan   tokenLifespan = new TimeSpan(0, Int32.Parse(ConfigurationManager.AppSettings["tokenLifespan_minutes"]), 0);

            if (actionContext.Request.Headers == null ||
                !actionContext.Request.Headers.Contains("Authorization-Token") ||
                string.IsNullOrEmpty(actionContext.Request.Headers.GetValues("Authorization-Token").FirstOrDefault()))

            {
                throw new HttpResponseException(actionContext.Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            string token = actionContext.Request.Headers.GetValues("Authorization-Token").FirstOrDefault();
            AuthenticationEntity authentication = dbContext.AuthenticationRepo.GetSingleOrDefault(token);

            if (authentication == null || (authentication.LastSeen.Add(tokenLifespan) < DateTime.UtcNow))
            {
                throw new HttpResponseException(actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            authentication.LastSeen = DateTime.UtcNow;
            dbContext.AuthenticationRepo.Update(authentication);

            UserEntity user = dbContext.UsersRepo.GetSingleOrDefault(authentication.UserId);

            if (user == null)
            {
                throw new HttpResponseException(actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            actionContext.RequestContext.Principal = new SimplePrincipal(user.UserName, user.Id, user.Role);

            base.OnActionExecuting(actionContext);
        }
Пример #2
0
        public static GovTalkMessageEntity CreateBaseRequest(String serviceName, BaseMessageEntity message)
        {
            var auth = new AuthenticationEntity
            {
                Method = "clear",
                Value  = ConfigurationManager.AppSettings["GovTalkPassword"]
            };

            var idAuth = new IDAuthenticationEntity
            {
                SenderID       = ConfigurationManager.AppSettings["GovTalkUserName"],
                Authentication = auth,
            };

            var senderDetails = new SenderDetailsEntity
            {
                EmailAddress     = "nomail",
                IDAuthentication = idAuth,
            };

            var messageDetails = new MessageDetailsEntity
            {
                Class         = serviceName,
                Function      = "submit",
                Qualifier     = "request",
                CorrelationID = "cor",
            };

            var header = new HeaderEntity
            {
                SenderDetails  = senderDetails,
                MessageDetails = messageDetails,
            };

            var body = new BodyEntity
            {
                Entity = message,
            };

            var error = new ErrorEntity
            {
                EnvelopeVersion = "369.25",
                Number          = 2695,
                RaisedBy        = "me",
                Text            = "Exception",
                Type            = "TypedError"
            };

            var govTalkMessage = new GovTalkMessageEntity
            {
                EnvelopeVersion = 2.0M,
                Header          = header,
                Body            = body,
            };

            return(govTalkMessage);
        }
Пример #3
0
        public ResponseEntity login(AuthenticationEntity authenticationEntity)
        {
            try
            {
                ResponseEntity responseEntity = new ResponseEntity();

                var command = dBContext.Connection.CreateCommand() as SqlCommand;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "dbo.prcCheckUserLogin";
                command.Parameters.Add(new SqlParameter
                {
                    ParameterName = "@UID",
                    DbType        = DbType.String,
                    Value         = authenticationEntity.UserId,
                });
                command.Parameters.Add(new SqlParameter
                {
                    ParameterName = "@PWD",
                    DbType        = DbType.String,
                    Value         = hashPassword(authenticationEntity.Pwd),
                });

                List <IDictionary <String, Object> > result = dBContext.GetDatabaseResultSet(command);

                if (result != null)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap <IDictionary <String, Object>, List <DBResultEnity> >();
                    }).CreateMapper();
                    List <DBResultEnity> dBResult = config.Map <List <DBResultEnity> >(result);

                    DBResultEnity dBResultEnity = dBResult.FirstOrDefault();

                    responseEntity.StatusCode    = dBResultEnity.STATUSCODE;
                    responseEntity.StatusMessage = dBResultEnity.STATUSDESC;
                    if (dBResultEnity.STATUSCODE == 1)
                    {
                        responseEntity.ResponseResult = getJWTPacket(authenticationEntity.UserId);
                    }
                    return(responseEntity);
                }
                else
                {
                    responseEntity.StatusCode    = 0;
                    responseEntity.StatusMessage = "Failed";
                    return(responseEntity);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #4
0
        public async Task <string> Logout()
        {
            AuthenticationEntity authentication = await DbContext.AuthenticationRepo.GetSingleOrDefaultAsync(AuthenticationToken);

            if (authentication == null)
            {
                ThrowHttpResponseException(System.Net.HttpStatusCode.Unauthorized, "Wrong authentication token.");
            }

            await DbContext.AuthenticationRepo.DeleteAsync(AuthenticationToken);

            return(string.Format("Successful logout"));
        }
 public IHttpActionResult PostLogin([FromBody] AuthenticationEntity auth)
 {
     if (!ModelState.IsValid)
     {
         Log.Error("Model is in-valid for entry POST api/employee");
         throw WebExceptionFactory.GetBadRequestError("Model is in valid check your payload");
     }
     if (!_employeeService.AuthenticateUser(auth.username, auth.password))
     {
         Log.Info($"{auth.username} is not authenticated");
         throw WebExceptionFactory.GetBadRequestError("Model is in valid check your payload");
     }
     Log.Info($"{auth.username} has been authenticated");
     return(Ok());
 }
Пример #6
0
 public IActionResult Register([FromBody] AuthenticationEntity authEntity)
 {
     if (!ModelState.IsValid)
     {
         return(new JsonResult(BadRequest(ModelState)));
     }
     else
     {
         try
         {
             Authentication auth = new Authentication();
             return(new JsonResult(auth.register(authEntity)));
         }
         catch (Exception e)
         {
             return(new JsonResult(StatusCode(500, e.Message)));
         }
     }
 }