Exemplo n.º 1
0
        public IActionResult AuthenticateUser([FromBody] AuthBody authBody)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!_context.User.Any(u => authBody.mailAddress.Equals(u.mailAddress)))
            {
                return(NotFound());
            }

            var user = _context.User.First(u => u.mailAddress.Equals(authBody.mailAddress));

            if (BCrypt.Net.BCrypt.Verify(authBody.password, user.password))
            {
                var response = new AuthResponseBody()
                {
                    id          = user.id,
                    mailAddress = user.mailAddress,
                    team        = user.team,
                    username    = user.username
                };
                return(Ok(response));
            }
            else
            {
                return(BadRequest(new BasicResponse {
                    message = "Wrong password"
                }));
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> DefaultErrorHandler()
        {
            var exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (exceptionHandlerPathFeature != null && exceptionHandlerPathFeature.Error != null)
            {
                string emailNotificationErrMsg = "";

                try
                {
                    await ExceptionUtils.NotifySystemOps(exceptionHandlerPathFeature.Error,
                                                         _httpContext);
                }
                catch (Exception exc)
                {
                    // silence error
                    emailNotificationErrMsg = exc.ToString();
                }

                if (exceptionHandlerPathFeature.Error is ModelStateInvalidException)
                {
                    return(BadRequest((exceptionHandlerPathFeature.Error as ModelStateInvalidException).ModelState));
                }

                if (exceptionHandlerPathFeature.Error is AuthCodeFailException)
                {
                    return(Unauthorized());
                }

                if (exceptionHandlerPathFeature.Error is AuthenticateLicenseFailException)
                {
                    AuthResponseBody authResponseBody = (exceptionHandlerPathFeature.Error as AuthenticateLicenseFailException).AuthResponse;
                    // for testing sending email at production server
                    authResponseBody.EmailNotificationErrMsg = emailNotificationErrMsg;
                    return(Ok(authResponseBody));
                }
            }

            return(StatusCode(StatusCodes.Status500InternalServerError));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> AuthenticateLicense([FromBody][Bind("ApiAuthCode", "LicenseKey", "MacAddress")] AuthRequestBody authRequestBody)
        {
            if (!ModelState.IsValid)
            {
                throw new ModelStateInvalidException(authRequestBody as object, ModelState);
            }

            if (!IsAuthorised(authRequestBody.ApiAuthCode))
            {
                throw AuthCodeFailException.AuthCodeFailExceptionFactory(authRequestBody.ApiAuthCode);
            }

            var authResponseBody = new AuthResponseBody
            {
                IsAuthenticated = false
            };

            authRequestBody.MacAddress = NormalizeMacAddress(authRequestBody.MacAddress);

            var macAddressFromDb = await _dbContext.MacAddresses.FindAsync(authRequestBody.MacAddress);

            if (macAddressFromDb != null)
            {
                _dbContext.MacAddresses.Remove(macAddressFromDb);
                // save changes so that it won't affect licenseKeyFromDb.NumOfMacAddressesAllowed check later
                await _dbContext.SaveChangesAsync();
            }

            authResponseBody.IsAuthenticated = await AddNewMacAddressAsync(authRequestBody.MacAddress, authRequestBody.LicenseKey);

            await _dbContext.SaveChangesAsync();

            if (!authResponseBody.IsAuthenticated)
            {
                throw new AuthenticateLicenseFailException(authResponseBody);
            }

            return(Ok(authResponseBody));
        }
Exemplo n.º 4
0
 private static string ToMessage(AuthResponseBody authResponseBody)
 {
     return(authResponseBody.IsAuthenticated ?
            "Authenticate license succeeded." : "Authenticate license failed.");
 }
Exemplo n.º 5
0
 public AuthenticateLicenseFailException(AuthResponseBody authResponseBody) : base(ToMessage(authResponseBody))
 {
     AuthResponse = authResponseBody;
 }
 public AuthTokenResp Token([FromBody] AuthTokenReq authTokenReq)
 {
     ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)((_param1, _param2, _param3, _param4) => true);
     try
     {
         this.stringBuilder.Append(authTokenReq.Username);
         this.stringBuilder.Append(":");
         this.stringBuilder.Append(authTokenReq.Password);
         string str1 = "Basic " + AuthController.Base64Encode(this.stringBuilder.ToString());
         this.logger.Info("Starting::: Token Generation Calls. Header " + str1);
         if (str1.StartsWith("Basic"))
         {
             string[]    strArray1   = Encoding.UTF8.GetString(Convert.FromBase64String(str1.Substring("Basic ".Length).Trim())).Split(':');
             RestClient  restClient  = new RestClient(this.UserValidationBaseURL + "ValidateUserNew?Username="******"&Password="******"cache-control", "no-cache");
             restRequest.AddHeader("Content-Type", "application/json");
             IRestResponse    restResponse      = restClient.Execute((IRestRequest)restRequest);
             AuthResponseBody authResponseBody1 = new AuthResponseBody();
             AuthResponseBody authResponseBody2 = JsonConvert.DeserializeObject <AuthResponseBody>(restResponse.Content);
             if (authResponseBody2.Status == "00")
             {
                 string[] strArray2 = authResponseBody2.Result.Split('|');
                 this.logger.Info("Result::: DB Query Response " + authResponseBody2.Result);
                 if (strArray2[0] == "1" && strArray2[1] == "2")
                 {
                     Claim[] claimArray = new Claim[1]
                     {
                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", strArray1[0] + "|" + strArray2[1])
                     };
                     SigningCredentials signingCredentials = new SigningCredentials((SecurityKey) new SymmetricSecurityKey(Encoding.UTF8.GetBytes("jlklk;lkl;wkwipoiuwoulwlrwwqxdwfrr")), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256");
                     DateTime?          expires            = new DateTime?(DateTime.Now.AddMinutes(1.0));
                     string             str2 = new JwtSecurityTokenHandler().WriteToken((SecurityToken) new JwtSecurityToken("wemabank.com", "cbn.gov.ng", (IEnumerable <Claim>)claimArray, expires: expires, signingCredentials: signingCredentials));
                     this.authTokenResp = new AuthTokenResp()
                     {
                         ResponseCode    = this.successResponse.Status,
                         ResponseMessage = this.successResponse.Msg,
                         Token           = str2
                     };
                     return(this.authTokenResp);
                 }
             }
         }
         this.authTokenResp = new AuthTokenResp()
         {
             ResponseCode    = this.errorResponse.Status,
             ResponseMessage = this.errorResponse.Msg,
             Token           = ""
         };
         return(this.authTokenResp);
     }
     catch (Exception ex)
     {
         this.logger.Info("Entering Exceptions::: message:-" + ex.Message);
         this.authTokenResp = new AuthTokenResp()
         {
             ResponseCode    = this.errorResponse.Status,
             ResponseMessage = this.errorResponse.Msg,
             Token           = ex.Message
         };
         return(this.authTokenResp);
     }
 }