/// <summary>
        /// Authenicates a user based on the information in the HTTP request.
        /// </summary>
        /// <returns></returns>
        public override void Authenticate(AuthenticationRequest request, AuthenticationResponse response)
        {
            // Only execute the authentication if the user is not known yet

            if (response.Principal == null)
            {
                // Get OpenID provider's response from the http context
                using (var openid = new OpenIdRelyingParty())
                {
                    var openIDResponse = openid.GetResponse();

                    // TODO: figure out which OpenID provider sent the response
                    // and associate with the right authenticator

                    if (response != null)
                    {
                        switch (openIDResponse.Status)
                        {
                            case AuthenticationStatus.Authenticated:
                                response.SetPrincipal(CreatePrincipal(openIDResponse));
                                break;
                            case AuthenticationStatus.Canceled:
                            case AuthenticationStatus.Failed:
                                throw new System.Security.Authentication.AuthenticationException("OpenID authentication failed.", openIDResponse.Exception); // TODO
                            case AuthenticationStatus.ExtensionsOnly:
                            case AuthenticationStatus.SetupRequired:
                                throw new InvalidOperationException();
                            default:
                                throw new NotImplementedException();
                        }
                    }
                }
            }
        }
        public bool Authenticate(string login, string password,
            out AuthenticationResponse response, out string authStatusString)
        {
            AccountStatus.Instance.connectionStatus = AccountConnectionStatus.NotConnected;
            AccountStatus.Instance.Login = login;
            try
            {
                var localTime = DateTime.Now.Ticks;
                var hash = CredentialsHash.MakeCredentialsHash(login, password, localTime);
                int sessionTag;
                response = serverProxyTrade.proxy.Authenticate(login, hash, terminalVersion,
                                                                UserSettings.Instance.TerminalId, localTime,
                                                                out sessionTag);
                // обновить контекст безопасности
                if (response == AuthenticationResponse.OK)
                    CurrentProtectedContext.Instance.OnAuthenticated(sessionTag);
                else
                    CurrentProtectedContext.Instance.OnAuthenticateFaulted();
            }
            catch (Exception ex)
            {
                response = AuthenticationResponse.ServerError;
                Logger.ErrorFormat("Ошибка аутентификации {0}", ex);
                authStatusString = EnumFriendlyName<AuthenticationResponse>.GetString(response);
                AccountStatus.Instance.connectionStatus = AccountConnectionStatus.ConnectionError;
                AccountStatus.Instance.isAuthorized = false;
                return false;
            }
            authStatusString = EnumFriendlyName<AuthenticationResponse>.GetString(response);

            if (new[] {AuthenticationResponse.AccountInactive, AuthenticationResponse.InvalidAccount,
                    AuthenticationResponse.ServerError, AuthenticationResponse.WrongPassword, AuthenticationResponse.NotAuthorized}.Contains(response))
            {
                AccountStatus.Instance.isAuthorized = false;
                AccountStatus.Instance.connectionStatus = AccountConnectionStatus.ConnectionError;
                return false;
            }

            // аутентификация успешна
            MainWindowTitle.Instance.UserTitle = login;
            AccountStatus.Instance.connectionStatus = AccountConnectionStatus.Connected;
            AccountStatus.Instance.isAuthorized = true;
            authStatusString = "Connected";
            // выполнить ряд действий, доступных после подключения
            OnAuthenticated();
            return true;
        }
        public override void Authenticate(AuthenticationRequest request, AuthenticationResponse response)
        {
            // Keystone tokens (in the simplest case) do not carry any detailed
            // information about the identity of the user. For this reason,
            // every token needs to be validated by calling the Keystone service.
            // To avoid doing this, we need to cache tokens.

            // Look for a token in the request headers
            var tokenID = request.Headers[settings.AuthTokenHeader];

            if (tokenID == null)
            {
                // Try to take header from the query string
                tokenID = request.QueryString[settings.AuthTokenParameter];
            }

            if (tokenID != null)
            {
                Token token;

                // Check if the resolved token is already in the cache
                if (!tokenCache.TryGetValue(tokenID, out token))
                {
                    // Need to validate token against Keystone
                    var ksclient = settings.CreateClient();

                    token = new Token()
                    {
                        ID = tokenID
                    };

                    // Keystone doesn't return the user along with
                    // the token, so let's retrieve it now.

                    // TODO: this part might need modifications
                    // if we also accept trusts
                    token.User = ksclient.GetUser(token);

                    tokenCache.TryAdd(token.ID, token);
                }

                settings.UpdateAuthenticationResponse(response, token, IsMasterAuthority);
            }
        }
Пример #4
0
        public async Task <bool> LoginAsync(string userName, string password)
        {
            var auth = new AuthenticationRequest
            {
                UserID   = userName,
                Password = password,
                MacAddr  = ""
            };

            UriBuilder builder = new UriBuilder(GlobalSettings.AuthenticationEndpoint);

            builder.Path = "MyPatchAPI/api/verifylogin";

            string uri = builder.ToString();

            AuthenticationResponse authenticationInfo = await _requestProvider.PostAsync <AuthenticationRequest, AuthenticationResponse>(uri, auth);

            Settings.UserId     = authenticationInfo.User_ID;
            Settings.UserType   = authenticationInfo.User_Type;
            Settings.UserActive = authenticationInfo.IsActive;
            Settings.UserMsg    = authenticationInfo.User_Msg;

            return(true);
        }
        public async Task<ActionResult> MSLoginCallback(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {
                AuthenticationResponse r = new AuthenticationResponse();
                r.code = code;
                RP.CurrentSession = HttpContext.Session;
                /* verify the logic */
                RP.SignInRP(r);
                if (RP.IsVerified())
                {
                    string userID = RP.GetUserID();
                   // string userID = "2672633b99598c2b366a437dc797ae4d";
                    var user = await UserManager.FindByNameAsync(userID);

                    if (user == null)
                    {

                        byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
                        byte[] key = Guid.NewGuid().ToByteArray();
                        string token = Convert.ToBase64String(time.Concat(key).ToArray());

                        string name = userID;

                        ViewBag.name = name;
                        ViewBag.token = token;
                        return View("MSLoginConfirmation");
                    }
                    else
                    {
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            return RedirectToAction("Index", "Home");
        }
Пример #6
0
        public FitbitClient(AuthenticationResponse authenticationResponse)
        {
            this.Authentication = new Authentication(authenticationResponse);

            this.HeartRate = new HeartRate(Authentication);
        }
Пример #7
0
        //private async Task DeviceInfo()
        //{
        //    try
        //    {
        //        var device = new Models.Device
        //        {
        //            SN = CrossDeviceInfo.Current.Id,
        //            Type = CrossDeviceInfo.Current.Idiom.ToString(),
        //            Model = CrossDeviceInfo.Current.Model,
        //            Platform = CrossDeviceInfo.Current.Platform.ToString(),
        //            Version = CrossDeviceInfo.Current.VersionNumber.ToString()
        //        };

        //        var deviceEntity = await _deviceDataService.AddDevice(device);

        //        if (deviceEntity.DeviceID != 0)
        //        {
        //            _settingsService.DeviceIdSettings = deviceEntity.DeviceID.ToString();
        //        }
        //        else
        //        {
        //            var deviceFromDatabase = await _deviceDataService.GetDeviceWithSN(device.SN);
        //            _settingsService.DeviceIdSettings = deviceFromDatabase.DeviceID.ToString();
        //        }

        //    }
        //    catch (HttpRequestExceptionEx)
        //    {

        //    }

        //}
        private async void LoginWithBarcode(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(_settingsService.UserNameSetting))
            {
                IsBusy = true;
                var dialog = _dialogService.ShowProgressDialog("Logging in... ");
                dialog.Show();
                if (_connectionService.IsConnected)
                {
                    try
                    {
                        AuthenticationResponse authenticationResponse =
                            await _authenticationService.Authenticate(username, password);

                        if (authenticationResponse.IsAuthenticated)
                        {
                            var timeWhenUserLogged = await _jobDataService.GetServerDateTime();

                            // we store the Id to know if the user is already logged in to the application
                            _settingsService.UserIdSetting   = authenticationResponse.User.Id.ToString();
                            _settingsService.UserNameSetting = authenticationResponse.User.Angajat;
                            var strSector = string.Empty;
                            var idSector  = authenticationResponse.User.IdSector;
                            if (idSector == 1)
                            {
                                strSector = "Confection";
                            }
                            else if (idSector == 2)
                            {
                                strSector = "Stiro";
                            }
                            else if (idSector == 6)
                            {
                                strSector = "Ramendo";
                            }
                            else if (idSector == 7)
                            {
                                strSector = "Tessitura";
                            }
                            else if (idSector == 8)
                            {
                                strSector = "Sartoria";
                            }
                            _settingsService.UserSectorSettings    = strSector;
                            _settingsService.UserLineSettings      = authenticationResponse.User.Linie;
                            _settingsService.UserLoginDateSettings = timeWhenUserLogged.ToString();
                            IsBusy = false;
                            var user = authenticationResponse.User;
                            user.Active         = true;
                            user.LastTimeLogged = timeWhenUserLogged;
                            await _userService.UpdateUserActivity(user.Id.ToString(), user);

                            //await DeviceInfo();
                            await _navigationService.NavigateToAsync <MainViewModel>();
                        }
                        dialog.Hide();
                    }
                    catch (HttpRequestExceptionEx e)
                    {
                        dialog.Hide();
                        await _navigationService.NavigateToAsync <LoginViewModel>();

                        await _dialogService.ShowDialog(
                            $"This username/password combination isn't known. HTTP Code: {e.HttpCode} Error Message: {e.Message}",
                            "Error logging you in",
                            "OK");
                    }
                    catch (Exception exception)
                    {
                        dialog.Hide();
                        await _navigationService.NavigateToAsync <LoginViewModel>();

                        await _dialogService.ShowDialog(
                            $"Unknown error occured: {exception.Message}",
                            "Error logging you in",
                            "OK");
                    }
                }
                else
                {
                    dialog.Hide();
                    await _navigationService.NavigateToAsync <LoginViewModel>();

                    await _dialogService.ShowDialog(
                        "Connection problem please try again later.",
                        "Internet connection problem",
                        "OK");
                }
            }
            else
            {
                await _navigationService.NavigateToAsync <MainViewModel>();

                await _dialogService.ShowDialog(
                    $"User already logged in with name {_settingsService.UserNameSetting}, please logout to change user account",
                    "User logged", "OK");
            }
        }
Пример #8
0
 private void SetUser(AuthenticationResponse auth)
 {
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.Token);
 }
Пример #9
0
        // As client
        private HttpResponse SendHandshakeRequest()
        {
            var req = CreateHandshakeRequest();
            var res = SendHttpRequest(req, 90000);

            if (res.IsUnauthorized)
            {
#if AUTHENTICATION
                var chal = res.Headers["WWW-Authenticate"];
                Log.Warn(String.Format("Received an authentication requirement for '{0}'.", chal));
                if (chal.IsNullOrEmpty())
                {
                    Log.Error("No authentication challenge is specified.");
                    return res;
                }

                _authChallenge = AuthenticationChallenge.Parse(chal);
                if (_authChallenge == null)
                {
                    Log.Error("An invalid authentication challenge is specified.");
                    return res;
                }

                if (_credentials != null &&
                    (!_preAuth || _authChallenge.Scheme == AuthenticationSchemes.Digest))
                {
                    if (res.HasConnectionClose)
                    {
                        releaseClientResources();
                        setClientStream();
                    }

                    var authRes = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount);
                    _nonceCount = authRes.NonceCount;
                    req.Headers["Authorization"] = authRes.ToString();
                    res = sendHttpRequest(req, 15000);
                }
#else
                throw new InvalidOperationException("Authentication is not supported");
#endif
            }


            if (res.IsRedirect)
            {
                var url = res.Headers["Location"];
#if COMPAT
                Log.WarnFormat("Received a redirection to '{0}'.", url);
#else
                $"Received a redirection to '{url}'.".Warn();
#endif

                if (_enableRedirection)
                {
                    if (string.IsNullOrEmpty(url))
                    {
#if COMPAT
                        Log.Error("No url to redirect is located.");
#else
                        "No url to redirect is located.".Error();
#endif
                        return res;
                    }

                    Uri uri;
                    string msg;
                    if (!url.TryCreateWebSocketUri(out uri, out msg))
                    {
#if COMPAT
                        Log.Error("An invalid url to redirect is located: " + msg);
#endif
                        return res;
                    }

                    ReleaseClientResources();

                    _uri = uri;
                    IsSecure = uri.Scheme == "wss";

                    SetClientStream();
                    return SendHandshakeRequest();
                }
            }

            return res;
        }
Пример #10
0
    // As client
    private HttpResponse sendHandshakeRequest ()
    {
      var req = createHandshakeRequest ();
      var res = sendHttpRequest (req, 90000);
      if (res.IsUnauthorized) {
        var chal = res.Headers["WWW-Authenticate"];
        _logger.Warn (String.Format ("Received an authentication requirement for '{0}'.", chal));
        if (chal.IsNullOrEmpty ()) {
          _logger.Error ("No authentication challenge is specified.");
          return res;
        }

        _authChallenge = AuthenticationChallenge.Parse (chal);
        if (_authChallenge == null) {
          _logger.Error ("An invalid authentication challenge is specified.");
          return res;
        }

        if (_credentials != null &&
            (!_preAuth || _authChallenge.Scheme == AuthenticationSchemes.Digest)) {
          if (res.HasConnectionClose) {
            releaseClientResources ();
            setClientStream ();
          }

          var authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
          _nonceCount = authRes.NonceCount;
          req.Headers["Authorization"] = authRes.ToString ();
          res = sendHttpRequest (req, 15000);
        }
      }

      if (res.IsRedirect) {
        var url = res.Headers["Location"];
        _logger.Warn (String.Format ("Received a redirection to '{0}'.", url));
        if (_enableRedirection) {
          if (url.IsNullOrEmpty ()) {
            _logger.Error ("No url to redirect is located.");
            return res;
          }

          Uri uri;
          string msg;
          if (!url.TryCreateWebSocketUri (out uri, out msg)) {
            _logger.Error ("An invalid url to redirect is located: " + msg);
            return res;
          }

          releaseClientResources ();

          _uri = uri;
          _secure = uri.Scheme == "wss";

          setClientStream ();
          return sendHandshakeRequest ();
        }
      }

      return res;
    }
        public AuthenticationResponse Logout([FromHeader] BaseHeader header)
        {
            AuthenticationResponse authenResponse = _accountProcess.LogoutProcess(header.Authorization.Substring("Bearer".Length).Trim());

            return(authenResponse);
        }
        public AuthenticationResponse Authenticate(string email, string password, string ipAddress, string origin, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var authResponse = new AuthenticationResponse();

            //From here you may log the fact that the user has authenticated at this time (if this is something you wish to track)
            //login.IP; <-- IP address for logging purposes

            var result = PlatformSecurityManager.AuthenticateUser(email, password);

            authResponse.isSuccess    = result.isSuccess;
            authResponse.ErrorMessage = result.ErrorMessage;

            if (result.isSuccess)
            {
                //Get the IdentityUser from the ResponseObject:
                var platformUserIdentity = (PlatformUserIdentity)result.ResponseObject;


                //Convert to non Identity version & add to response object:
                authResponse.PlatformUser = PlatformUserManager.TransformPlatformUserIdentityToPlatformUser(platformUserIdentity);

                //Get Claims based identity for the user
                System.Security.Claims.ClaimsIdentity identity = PlatformUserManager.GetUserClaimsIdentity(
                    platformUserIdentity,
                    DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

                // You can add to claims thusly:
                //identity.AddClaim(new Claim(ClaimTypes.Name, "Name"));

                authResponse.ClaimsIdentity = identity;

                #region Log Platform user Activity (AuthenticationPassed)

                try
                {
                    PlatformLogManager.LogActivity(
                        CategoryType.Authentication,
                        ActivityType.Authentication_Passed,
                        "Successfull log in.",
                        authResponse.PlatformUser.FirstName + " successfully logged in.",
                        null,
                        null,
                        authResponse.PlatformUser.Id,
                        authResponse.PlatformUser.FirstName,
                        authResponse.PlatformUser.Email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }
            else
            {
                #region Log Platform User Activity (AuthenticationFailed)

                try
                {
                    PlatformLogManager.LogActivity(
                        CategoryType.Authentication,
                        ActivityType.Authentication_Failed,
                        "An attempt to log into the platform admin with email '" + email + "' has failed.",
                        result.ErrorMessage,
                        null,
                        null,
                        "Unknown",
                        "Unknown",
                        email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }

            return(authResponse);
        }
Пример #13
0
        public async Task <AuthenticationResponse> Register([FromBody] UserRequest userInfo)
        {
            AuthenticationResponse resp = new AuthenticationResponse();

            try
            {
                resp = await facade.Register(userInfo);

                if (resp.IsSuccess)
                {
                    #region Sent Email to User
                    SendEmail sendEmail    = new SendEmail(_emailConfiguration);
                    string    contentEmail = configFacade.GetRedaksionalEmail("ContentEmailRegistration").Result;
                    string    subjectEmail = configFacade.GetRedaksionalEmail("SubjectEmailRegistration").Result;

                    EmailAddress emailAddress = new EmailAddress();
                    emailAddress.Address = userInfo.Email;
                    emailAddress.Name    = userInfo.FirstName + " " + userInfo.LastName;
                    List <EmailAddress> listEmailAddress = new List <EmailAddress>();
                    listEmailAddress.Add(emailAddress);

                    string token = facade.GenerateToken(userInfo.Email);

                    string url = ui_url + "activationaccount?token=" + token;
                    //string url = ui_url.Contains(Request.Host.Value) ? ui_url + "activationaccount?token=" + token
                    //    : admin_url + "Identity/Account/activationaccount?token=" + token;
                    //string url = admin_url + "Identity/Account/activationaccount?token=" + token;
                    contentEmail = contentEmail.Replace("[user]", emailAddress.Name);
                    contentEmail = contentEmail.Replace("[Link]", url);

                    EmailAddress emailAddressFrom = new EmailAddress();
                    emailAddressFrom.Address = "*****@*****.**";
                    emailAddressFrom.Name    = "Lojualguebeli.com";
                    List <EmailAddress> listEmailAddressFrom = new List <EmailAddress>();
                    listEmailAddressFrom.Add(emailAddressFrom);

                    EmailMessage emailMessage = new EmailMessage();
                    emailMessage.ToAddresses   = listEmailAddress;
                    emailMessage.Subject       = subjectEmail;
                    emailMessage.FromAddresses = listEmailAddressFrom;
                    emailMessage.Content       = contentEmail;

                    sendEmail.Send(emailMessage);

                    #region testing email local victor
                    //sendEmail.Send(emailMessage);
                    //testing local victor
                    MailMessage mail = new MailMessage();
                    //SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                    //mail.From = new MailAddress("*****@*****.**");
                    //mail.To.Add(emailAddress.Address);
                    //mail.Subject = "Activation Password";
                    //mail.Body = contentEmail;
                    //mail.IsBodyHtml = true;

                    //SmtpServer.Port = 587;
                    //SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Lojualguebeli.com");
                    //SmtpServer.EnableSsl = true;

                    //SmtpServer.Send(mail);
                    #endregion

                    #endregion
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                resp.IsSuccess = false;
                resp.Message   = ex.Message;
            }

            return(resp);
        }
Пример #14
0
        private static void SocketServer_NewSessionConnected(WebSocketSession session)
        {
            var authenticateResponse = new AuthenticationResponse
            {
                ExecuteSuccess = true,
                ServerFeatures = WebSocketServerFeature.Instance.GetFeatures()
            };

            session.Send(JsonConvert.SerializeObject(authenticateResponse));
            Console.WriteLine("Connection accepted");
        }
Пример #15
0
        public static AuthenticationResponse AdCallForNameEmail(AuthenticationRequest request)
        {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse();

            try
            {
                ADService.Service Adservice = new ADService.Service();
                Adservice.Url = ConfigurationManager.AppSettings["ADServiceURL"];

                if (Helper.IsTest())
                {
                    string response = Adservice.ADUserDetails(request.UserID);
                    if (!string.IsNullOrEmpty(response))
                    {
                        string[] ResponseArray = response.Split('|');
                        if (ResponseArray != null)
                        {
                            string[] list = ResponseArray[0].Split(" ".ToCharArray());
                            authenticationResponse.FirstName = list[0];
                            authenticationResponse.LastName  = list.Length > 2 ? list[2] : list[1];
                            if (ResponseArray[1] != null)
                            {
                                authenticationResponse.Email = ResponseArray[1];
                            }
                            authenticationResponse.ResponseCode        = "0";
                            authenticationResponse.ResponseDescription = "Success";
                        }
                        else
                        {
                            authenticationResponse.ResponseCode        = "1001";
                            authenticationResponse.ResponseDescription = "User not authorized.";
                        }
                        return(authenticationResponse);
                    }
                }
                else
                {
                    string response = Adservice.ADValidateUser(request.UserID, request.Password);
                    if (!string.IsNullOrEmpty(response))
                    {
                        string[] ResponseArray = response.Split('|');
                        if (ResponseArray != null)
                        {
                            if (ResponseArray[0] == "true")
                            {
                                string[] list = ResponseArray[1].Split(" ".ToCharArray());
                                authenticationResponse.FirstName = list[0];
                                authenticationResponse.LastName  = list.Length > 2 ? list[2] : list[1];
                                string _response = Adservice.ADUserDetails(request.UserID);
                                if (_response != null)
                                {
                                    string[] _responseArray = _response.Split('|');
                                    if (_responseArray[1] != null)
                                    {
                                        authenticationResponse.Email = _responseArray[1];
                                    }
                                    authenticationResponse.ResponseCode        = "0";
                                    authenticationResponse.ResponseDescription = "Success";
                                }
                            }
                            else
                            {
                                authenticationResponse.ResponseCode        = "1001";
                                authenticationResponse.ResponseDescription = "User not authorized.";
                            }
                        }
                        return(authenticationResponse);
                    }
                }
            }
            catch (Exception ex)
            {
                if (request != null)
                {
                    request.Password = "******";
                }

                authenticationResponse.ResponseCode        = "1001";
                authenticationResponse.ResponseDescription = "Unable Authenticate the user. Please contact the administrator";
            }

            return(authenticationResponse);
        }
Пример #16
0
        // As client
        private void sendProxyConnectRequest()
        {
            var req = HttpRequest.CreateConnectRequest (_uri);
              var res = sendHttpRequest (req, 90000);
              if (res.IsProxyAuthenticationRequired) {
            var chal = res.Headers["Proxy-Authenticate"];
            _logger.Warn (
              String.Format ("Received a proxy authentication requirement for '{0}'.", chal));

            if (chal.IsNullOrEmpty ())
              throw new WebSocketException ("No proxy authentication challenge is specified.");

            var authChal = AuthenticationChallenge.Parse (chal);
            if (authChal == null)
            {

            try
            {
                var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_proxyUri);
                System.Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                request.Method = "CONNECT";

                var response = request.GetResponse();
                var responseStream = response.GetResponseStream();

                const System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;

                var rsType = responseStream.GetType();
                var connectionProperty = rsType.GetProperty("Connection", Flags);

                var connection = connectionProperty.GetValue(responseStream, null);
                var connectionType = connection.GetType();
                var networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags);

                var networkStream = networkStreamProperty.GetValue(connection, null);
                var nsType = networkStream.GetType();
                var socketProperty = nsType.GetProperty("Socket", Flags);
                var socket = (Socket)socketProperty.GetValue(networkStream, null);
                socket.Disconnect(true);
                _tcpClient = new TcpClient { Client = socket };
                _tcpClient.BeginConnect(_uri.DnsSafeHost, _uri.Port, new AsyncCallback(OnProxySocketConnected), _tcpClient);
                if (_ProxyTimeoutObject.WaitOne(_ProxySocketTimeoutMSec, false))
                {
                    if (_ProxySocketConnectionSuccessful)
                    {
                        _stream = _tcpClient.GetStream();
                    }
                    else
                    {
                        throw _ProxySocketException;
                    }
                }
                else
                {
                    _tcpClient.Close();
                    throw new TimeoutException("Socket Timeout Exception");
                }
            }
            catch (System.Net.WebException exception)
            {
                _logger.Error(exception.ToString());
            }
            }
            else if(_proxyCredentials != null){
              if (res.HasConnectionClose) {
            releaseClientResources ();
            _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
            _stream = _tcpClient.GetStream ();
              }

              var authRes = new AuthenticationResponse (authChal, _proxyCredentials, 0);
              req.Headers["Proxy-Authorization"] = authRes.ToString ();
              res = sendHttpRequest (req, 15000);

              if (res.IsProxyAuthenticationRequired)
            throw new WebSocketException ("A proxy authentication is required.");

              if (res.StatusCode[0] != '2')
              throw new WebSocketException(
                "The proxy has failed a connection to the requested host and port.");
            }
              }
        }
        public override AuthenticationResponse VerifyPassword(AuthenticationRequest request)
        {
            // User needs to be authenticated in the scope of a project (tenant).
            // Since a tenant with the same name is generated for each user in keystone, we
            // use the username as project name.
            var project = new Keystone.Project()
            {
                Domain = new Keystone.Domain()
                {
                    Name = settings.Domain.ToLowerInvariant()
                },
                Name = request.Username.ToLowerInvariant()
            };

            // Verify user password in Keystone, we don't use
            // Graywulf password in this case
            var token = KeystoneClient.Authenticate(settings.Domain.ToLowerInvariant(), request.Username.ToLowerInvariant(), request.Password, project);

            // Find user details in keystone
            token.User = GetKeystoneUser(request.Username);

            // Create a response, this sets necessary response headers
            var response = new AuthenticationResponse(request);
            settings.UpdateAuthenticationResponse(response, token, true);

            // Load user from the graywulf registry. This call will create the user
            // if necessary because authority is set to master
            LoadOrCreateUser(response.Principal.Identity);

            return response;
        }
Пример #18
0
        public void UpdateAuthenticationResponse(AuthenticationResponse response, Token token, bool isMasterAuthority)
        {
            if (response.Principal == null)
            {
                var principal = CreateAuthenticatedPrincipal(token.User, isMasterAuthority);
                response.SetPrincipal(principal);
            }

            // TODO: add keystone cookie, custom parameter, etc...
            response.QueryParameters.Add(authTokenParameter, token.ID);
            response.Headers.Add(authTokenHeader, token.ID);

            // TODO: not sure if it is needed or created automatically
            //response.Cookies.Add(CreateFormsAuthenticationTicketCookie(principal.Identity.User, createPersistentCookie));
        }
Пример #19
0
        public async Task <Response <AuthenticationResponse> > ExternalAuthenticateAsync(ExternalAuthRequest externalAuthRequest, string ipAddress)
        {
            ApplicationUser user = null;

            if (externalAuthRequest.Type == "google")
            {
                var GoogleApiTokenInfo = GetGoogleApiTokenInfo(externalAuthRequest);
                if (GoogleApiTokenInfo == null)
                {
                    throw new ApiException($"Invalid Credentials");
                }
                user = await _userManager.FindByEmailAsync(GoogleApiTokenInfo.email);

                if (user == null)
                {
                    user = new ApplicationUser
                    {
                        Email          = GoogleApiTokenInfo.email,
                        FirstName      = GoogleApiTokenInfo.given_name,
                        LastName       = GoogleApiTokenInfo.family_name,
                        UserName       = GoogleApiTokenInfo.sub,
                        EmailConfirmed = true,
                        ProfilePicture = null,
                        IsActive       = true
                    };
                    var result = await _userManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(user, Roles.Basic.ToString());
                    }
                    else
                    {
                        throw new ApiException($"Invalid Credentials");
                    }
                }
            }
            else if (externalAuthRequest.Type == "facebook")
            {
                var FacebookApiTokenInfo = GetFacebookApiTokenInfo(externalAuthRequest);
                if (FacebookApiTokenInfo == null)
                {
                    throw new ApiException($"Invalid Credentials");
                }
                user = await _userManager.FindByEmailAsync(FacebookApiTokenInfo.email);

                if (user == null)
                {
                    user = new ApplicationUser
                    {
                        Email          = FacebookApiTokenInfo.email,
                        FirstName      = FacebookApiTokenInfo.first_name,
                        LastName       = FacebookApiTokenInfo.last_name,
                        UserName       = FacebookApiTokenInfo.id,
                        EmailConfirmed = true,
                        ProfilePicture = null,
                        IsActive       = true
                    };
                    var result = await _userManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(user, Roles.Basic.ToString());
                    }
                    else
                    {
                        throw new ApiException($"Invalid Credentials");
                    }
                }
            }


            JwtSecurityToken jwtSecurityToken = await TokenHelper.GenerateJWToken(user, _userManager, _jwtSettings);

            AuthenticationResponse response = new AuthenticationResponse();

            response.Id          = user.Id;
            response.AccessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            response.Email       = user.Email;
            response.UserName    = user.UserName;
            var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

            response.Roles      = rolesList.ToList();
            response.IsVerified = user.EmailConfirmed;
            var refreshToken = TokenHelper.GenerateRefreshToken(ipAddress);

            response.RefreshToken = refreshToken.Token;
            return(new Response <AuthenticationResponse>(response, $"Authenticated {user.UserName}"));
        }
Пример #20
0
        /// <summary>
        /// Create application credentials bound to service account with given unique name and expiration time.
        /// </summary>
        /// <param name="requestedUserName">Username of the requester.</param>
        /// <returns>Created application credentials.</returns>
        public async Task <ApplicationCredentialsDTO> CreateApplicationCredentialsAsync(string requestedUserName, AuthenticationResponse authResponse)
        {
            string uniqueTokenName  = requestedUserName + '_' + Guid.NewGuid();
            var    sessionExpiresAt = DateTime.UtcNow.AddSeconds(OpenStackSettings.OpenStackSessionExpiration);

            var    requestObject = ApplicationCredentialsRequest.CreateApplicationCredentialsRequest(uniqueTokenName, sessionExpiresAt);
            string requestBody   = JsonConvert.SerializeObject(requestObject, IgnoreNullSerializer.Instance);

            RestRequest restRequest = new RestRequest($"v{OpenStackSettings.OpenStackVersion}/users/{authResponse.Token.User.Id}/application_credentials", Method.Post)
                                      .AddStringBody(requestBody, DataFormat.Json)
                                      .AddXAuthTokenToHeader(authResponse.AuthToken);

            RestResponse response = await _basicRestClient.ExecuteAsync(restRequest);

            ApplicationCredentialsResponse result = ParseHelper.ParseJsonOrThrow <ApplicationCredentialsResponse, OpenStackAPIException>(response, HttpStatusCode.Created);

            return(new ApplicationCredentialsDTO
            {
                ApplicationCredentialsId = result.ApplicationCredentials.Id,
                ApplicationCredentialsSecret = result.ApplicationCredentials.Secret,
                ExpiresAt = sessionExpiresAt
            });
        }
Пример #21
0
        // As client
        private HandshakeRequest createHandshakeRequest()
        {
            var path = _uri.PathAndQuery;
              var host = _uri.Port == 80 ? _uri.DnsSafeHost : _uri.Authority;

              var req = new HandshakeRequest (path);
              var headers = req.Headers;

              headers ["Host"] = host;

              if (!_origin.IsNullOrEmpty ())
            headers ["Origin"] = _origin;

              headers ["Sec-WebSocket-Key"] = _base64Key;

              if (_protocols != null)
            headers ["Sec-WebSocket-Protocol"] = _protocols.ToString (", ");

              var extensions = createExtensionsRequest ();
              if (extensions != null)
            headers ["Sec-WebSocket-Extensions"] = extensions;

              headers ["Sec-WebSocket-Version"] = _version;

              AuthenticationResponse authRes = null;
              if (_authChallenge != null && _credentials != null) {
            authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
            _nonceCount = authRes.NonceCount;
              }
              else if (_preAuth)
            authRes = new AuthenticationResponse (_credentials);

              if (authRes != null)
            headers ["Authorization"] = authRes.ToString ();

              if (_cookies.Count > 0)
            req.SetCookies (_cookies);

              return req;
        }
Пример #22
0
        private void button9_Click(object sender, EventArgs e)
        {
            if (!login == true)
            {
                string labase = null;
                if (File.Exists(appdatafile))
                {
                    if (Directory.Exists(File.ReadAllText(appdatafile)))
                    {
                        labase = File.ReadAllText(appdatafile);
                    }
                }

                if (String.IsNullOrEmpty(labase))
                {
                    labase = @"c:\launcher\";
                }

                textBox1.Text = labase;
            }
            else
            {
                Request authRequest = new Request(Request.Method.POST, URL.AUTHENTICATION.SIGN_IN);
                String  rawResponse = authRequest.Execute((string)Header.Authentication.Signin(textBox1.Text, textBox2.Text));
                AuthenticationResponse authResponse = new AuthenticationResponse(rawResponse);


                if (authResponse.GetResponse.Error == null)
                {
                    checkBox1.Hide();
                    MessageBox.Show("Bonjour " + authResponse.GetResponse.PlayerName);
                    //              Console.WriteLine("  AccessToken:" +  authResponse.GetResponse.AccessToken);
                    //              Console.WriteLine("  ClientToken: "+  authResponse.GetResponse.ClientToken);
                    button9.Hide();

                    label2.Hide();
                    textBox1.Hide();
                    textBox2.Hide();
                    checkBox1.Hide();
                    label3.Hide();
                    if (File.Exists(follow))
                    {
                        File.Delete(follow);
                    }


                    if (checkBox1.Checked == true)
                    {
                        MessageBox.Show("textbox coché");
                        // chekbox egal à true
                        //  + "username=@" + authResponse.GetResponse.PlayerName + "@"
                        File.WriteAllText(follow, "true");
                    }
                    else
                    {
                        MessageBox.Show("checkbox pas coché");
                        File.WriteAllText(follow, "false");
                    }

                    // écriture du account.json



                    client = "{\"accounts\":[{ \"accessToken\":\" " + "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwMzkyOTgxMTgxMWFiZTJhODRjOWEwZWQwNzNiMTY5YyIsInlnZ3QiOiJlNDI4OWY3MmQ3N2Y0ZTI0YWVkMzc3Y2I1NjA1ZjI1NiIsInNwciI6IjNjMjI5OTk5NDg2OTQ0ZDY4YjY4MmU1NDczNmEwZGRmIiwiaXNzIjoiWWdnZHJhc2lsLUF1dGgiLCJleHAiOjE2MTQ1MTczNzUsImlhdCI6MTYxNDM0NDU3NX0.TJmzaPF70bul0nTAal6Bj6a_soB1oT0bHnFoTF9rSOk" + "\",\"activeProfiles\":\"3c229999486944d68b682e54736a0ddf\", \"clientToken\":\"" + authResponse.GetResponse.ClientToken + "\",\"profiles\":[{\"id\":\"3c229999486944d68b682e54736a0ddf\",\"legacy\": false,\"name\":\"" + authResponse.GetResponse.PlayerName + "\"}],\"user\":{\"id\":\"03929811811abe2a84c9a0ed073b169c\"}, \"username\":\"" + textBox1.Text + "\"}],\"activeAccount\":\"" + textBox1.Text + "\",\"formatVersion\": 2}";
                    Console.WriteLine(authResponse.GetResponse.AccessToken);
                    Console.WriteLine(authResponse.GetResponse.ClientToken);
                    Console.WriteLine(authResponse.GetResponse.PlayerName);


                    File.WriteAllText(@"C:\Users\Maxime\Desktop\MultiMC\accounts.json", client);
                }
                else
                {
                    MessageBox.Show("Authentication failed.");
                    Console.WriteLine("PlayerName: " + authResponse.GetResponse.PlayerName);
                    Console.WriteLine("  ErrorType: " + authResponse.GetResponse.Error);
                    Console.WriteLine("  ErrorMessage: " + authResponse.GetResponse.ErrorMessage);
                }
            }
        }
Пример #23
0
    // As client
    private HttpRequest createHandshakeRequest ()
    {
      var ret = HttpRequest.CreateWebSocketRequest (_uri);

      var headers = ret.Headers;
      if (!_origin.IsNullOrEmpty ())
        headers["Origin"] = _origin;

      headers["Sec-WebSocket-Key"] = _base64Key;

      if (_protocols != null)
        headers["Sec-WebSocket-Protocol"] = _protocols.ToString (", ");

      var exts = createExtensions ();
      if (exts != null)
        headers["Sec-WebSocket-Extensions"] = exts;

      headers["Sec-WebSocket-Version"] = _version;

      AuthenticationResponse authRes = null;
      if (_authChallenge != null && _credentials != null) {
        authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
        _nonceCount = authRes.NonceCount;
      }
      else if (_preAuth) {
        authRes = new AuthenticationResponse (_credentials);
      }

      if (authRes != null)
        headers["Authorization"] = authRes.ToString ();

      if (_cookies.Count > 0)
        ret.SetCookies (_cookies);

      return ret;
    }
Пример #24
0
        // As client
        private void sendProxyConnectRequest()
        {
            var req = HttpRequest.CreateConnectRequest (_uri);
              var res = sendHttpRequest (req, 90000);
              if (res.IsProxyAuthenticationRequired) {
            var authChal = res.ProxyAuthenticationChallenge;
            if (authChal != null && _proxyCredentials != null) {
              if (res.Headers.Contains ("Connection", "close")) {
            releaseClientResources ();
            _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
            _stream = _tcpClient.GetStream ();
              }

              var authRes = new AuthenticationResponse (authChal, _proxyCredentials, 0);
              req.Headers["Proxy-Authorization"] = authRes.ToString ();
              res = sendHttpRequest (req, 15000);
            }

            if (res.IsProxyAuthenticationRequired)
              throw new WebSocketException ("A proxy authentication is required.");
              }

              if (res.StatusCode[0] != '2')
            throw new WebSocketException (
              "The proxy has failed a connection to the requested host and port.");
        }
 public void SetAuthorization(AuthenticationResponse response)
 {
     var credentials = response.ToString ();
       AddHeader ("Authorization", credentials);
 }
Пример #26
0
        public async Task <IActionResult> LogInUserAsync([FromBody] UserPasswordLogIn logIn)
        {
            AuthenticationResponse response = new AuthenticationResponse();

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(logIn.Username);

                if (user != null)
                {
                    var login = await _signInManager.PasswordSignInAsync(user, logIn.Password, false, false);

                    if (login.Succeeded)
                    {
                        var code = RandomString();
                        _iMSDbContext.UserApiKeys.Add(new UserApiKey()
                        {
                            AuthToken = code, CreatedOn = DateTime.UtcNow, UserId = user.Id
                        });
                        await _iMSDbContext.SaveChangesAsync();

                        response.Response = new LoggedInUserDetail()
                        {
                            Username = user.UserName, Id = user.Id, Name = user.Name, UserAuthToken = code
                        };
                        return(Ok(new ApiServiceResponse()
                        {
                            Status = 200, Message = "Success", ResultObj = response
                        }));
                    }
                    else
                    {
                        response.ErrorMessage = "Incorrect Password";
                        return(BadRequest(new ApiServiceResponse()
                        {
                            Status = -100, Message = "Incorrect Password", ResultObj = response
                        }));
                    }
                }
                else
                {
                    response.ErrorMessage = "Seems like you haven't register with this username";
                    return(BadRequest(new ApiServiceResponse()
                    {
                        Status = -100, Message = "Seems like you haven't register with this username", ResultObj = response
                    }));
                }
            }
            else
            {
                if (string.IsNullOrEmpty(logIn.Username))
                {
                    response.ErrorMessage = "Username is required";
                }
                else
                {
                    response.ErrorMessage = "Password is required";
                }
                return(BadRequest(new ApiServiceResponse()
                {
                    Status = -100, Message = response.ErrorMessage, ResultObj = response
                }));
            }
        }
Пример #27
0
      public string CheckAuthentication(Guid uid, string token)
      {
          AuthenticationRequest logobj = new AuthenticationRequest();
          var check =
              _authresplog.AsQueryable <AuthenticationResponse>()
              //.Where(e => e.Status == "IN")
              .Where(e => e.UId == uid)
              .OrderByDescending(p => p.LoginTime);


          AuthenticationResponse authenticationresp  = new AuthenticationResponse();
          AuthenticationResponse authenticationrescp = new AuthenticationResponse();

          authenticationresp = check.FirstOrDefault();

          if (authenticationresp == null)
          {
              logobj.UId       = uid;
              logobj.Status    = "IN";
              logobj.JWTToken  = token;
              logobj.LoginTime = DateTime.Now;

              InsertLog(logobj);

              return("Success");
          }
          else if (authenticationresp.Status == "OUT" && authenticationresp.JWTToken == token)
          {
              return("Failed");
          }
          else if (authenticationresp.Status == "IN" && authenticationresp.JWTToken == token)
          {
              var update = Builders <AuthenticationResponse> .Update.Set(a => a.LoginTime, DateTime.Now);

              _authresplog.UpdateOne(model => model.Id == authenticationresp.Id, update);

              return("Success");
          }
          else if (authenticationresp.Status == "IN" && authenticationresp.JWTToken != token)
          {
              check =
                  _authresplog.AsQueryable <AuthenticationResponse>()

                  .Where(e => e.JWTToken == token)
                  .OrderByDescending(p => p.LoginTime);
              authenticationrescp = check.FirstOrDefault();

              if (authenticationrescp == null)
              {
                  var update = Builders <AuthenticationResponse> .Update.Set(a => a.Status, "OUT");

                  _authresplog.UpdateMany(model => model.UId == authenticationresp.UId, update);

                  logobj.UId       = uid;
                  logobj.Status    = "IN";
                  logobj.JWTToken  = token;
                  logobj.LoginTime = DateTime.Now;

                  InsertLog(logobj);
                  return("Success");
              }
              else if (authenticationrescp.Status == "OUT")
              {
                  return("Failed");
              }
              else
              {
                  return("Failed");
              }
          }
          else if (authenticationresp.Status == "OUT" && authenticationresp.JWTToken != token)
          {
              logobj.UId       = uid;
              logobj.Status    = "IN";
              logobj.JWTToken  = token;
              logobj.LoginTime = DateTime.Now;

              InsertLog(logobj);

              return("Success");
          }
          else
          {
              return("Failed");
          }
      }
Пример #28
0
        // As client
        private HttpRequest CreateHandshakeRequest()
        {
            var ret = HttpRequest.CreateWebSocketRequest(_uri);

            var headers = ret.Headers;
            if (!string.IsNullOrEmpty(_origin))
                headers["Origin"] = _origin;

            headers["Sec-WebSocket-Key"] = _base64Key;

            _protocolsRequested = _protocols != null;
            if (_protocolsRequested)
                headers["Sec-WebSocket-Protocol"] = string.Join(", ", _protocols);

            _extensionsRequested = _compression != CompressionMethod.None;
            if (_extensionsRequested)
                headers["Sec-WebSocket-Extensions"] = CreateExtensions();

            headers["Sec-WebSocket-Version"] = Version;

#if AUTHENTICATION
            AuthenticationResponse authRes = null;
            if (_authChallenge != null && _credentials != null)
            {
                authRes = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount);
                _nonceCount = authRes.NonceCount;
            }
            else if (_preAuth)
            {
                authRes = new AuthenticationResponse(_credentials);
            }

            if (authRes != null)
                headers["Authorization"] = authRes.ToString();
#endif

            if (CookieCollection.Count > 0)
                ret.SetCookies(CookieCollection);

            return ret;
        }
Пример #29
0
        public async Task <AuthenticationResponse> Authenticate(Credentials input)
        {
            var ret = new AuthenticationResponse();

            AuthenticatedSession session = null;
            AuthenticatedUser    user    = null;

            //generate URL for service call using your configured Okta Domain
            string url = string.Format("{0}/api/v1/authn", this.settings.Value.Domain);

            //build the package we're going to send to Okta
            var data = new OktaAuthenticationRequest()
            {
                username = input.PublicKey, password = input.PrivateKey
            };

            //serialize input as json
            var json = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

            //create HttpClient to communicate with Okta's web service
            using (HttpClient client = new HttpClient())
            {
                //Set the API key
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SSWS", this.settings.Value.ApiToken);

                //Post the json data to Okta's web service
                using (HttpResponseMessage res = await client.PostAsync(url, json))

                    //Get the response from the server
                    using (HttpContent content = res.Content)
                    {
                        //get json string from the response
                        var responseJson = await content.ReadAsStringAsync();

                        Console.WriteLine(responseJson);

                        //deserialize json into complex object
                        dynamic responseObj = JsonConvert.DeserializeObject(responseJson);

                        //determine if the returned status is success
                        if (responseObj.status == "SUCCESS")
                        {
                            //get session data
                            session = new AuthenticatedSession()
                            {
                                Token     = responseObj.sessionToken,
                                ExpiresAt = responseObj.expiresAt
                            };

                            //get user data
                            user = new AuthenticatedUser()
                            {
                                Id        = responseObj._embedded.user.id,
                                Login     = responseObj._embedded.user.login,
                                Locale    = responseObj._embedded.user.locale,
                                TimeZone  = responseObj._embedded.user.timeZone,
                                FirstName = responseObj._embedded.user.firstName,
                                LastName  = responseObj._embedded.user.lastName
                            };
                        }
                    }
            }

            //return results of the operation packaged in a AuthenticationResponse object
            var wasSuccess = session != null && user != null;

            return(new AuthenticationResponse()
            {
                WasSuccessful = wasSuccess,
                Message = wasSuccess ? "Success" : "Invalid username and password",

                Session = session,
                User = user
            });
        }
Пример #30
0
        private string LoginUser()
        {
            AuthenticationResponse _AuthenticationResponse = new AuthenticationResponse {
                Result = false
            };

            try
            {
                string m_LoginName  = string.Empty;
                string m_Password   = string.Empty;
                bool   m_IsRemember = false;
                if (Request.Form["EmailAddress"] != null && Request.Form["IsFB"] != null)
                {
                    string _UserEmail = Request.Form["EmailAddress"].ToString();
                    User   _ThisUser  = new User().GetUserDetails(_UserEmail, true);
                    m_LoginName  = _ThisUser.LoginName;
                    m_Password   = _ThisUser.Password;
                    m_IsRemember = false;
                }
                else
                {
                    m_LoginName  = Request.Form["LoginName"].ToString();
                    m_Password   = Request.Form["Password"].ToString();
                    m_IsRemember = Convert.ToBoolean(Request.Form["IsRemember"].ToString());
                }

                bool IsEmailLogin = IsValidEmail(m_LoginName);
                User m_UserDetails;

                if (IsEmailLogin)
                {
                    m_UserDetails = new User().AuthenticateUserWithEmail(m_LoginName, m_Password);
                }
                else
                {
                    m_UserDetails = new User().AuthenticateUser(m_LoginName, m_Password);
                }
                if (m_UserDetails != null)
                {
                    string ACCOUNT_STATUS = new UserAccountSettings().GetUserAccountSettings(m_UserDetails.UserID).AccoutStatus;

                    if (ACCOUNT_STATUS.ToUpper() == "A")
                    {
                        if (!m_IsRemember)
                        {
                            FormsAuthentication.RedirectFromLoginPage(m_UserDetails.UserID.ToString(), false);

                            if (m_UserDetails.Status == "A")
                            {
                                // Check if any unanswered Criteria questions
                                Criteria[] _UnAnsweredCriteriaQuestions = new Criteria().GetUnAnsweredQuestions(m_UserDetails.UserID);
                                _AuthenticationResponse.Result = true;
                                if (_UnAnsweredCriteriaQuestions.Count() == 0)
                                {
                                    _AuthenticationResponse.RedirectPath = "Web/Home";
                                }
                                else
                                {
                                    _AuthenticationResponse.RedirectPath = "Web/Criteria";
                                }
                            }
                            if (m_UserDetails.Status == "P")
                            {
                                _AuthenticationResponse.RedirectPath = "Web/Criteria";
                            }
                            if (m_UserDetails.Status == "I")
                            {
                                _AuthenticationResponse.RedirectPath = "Delete";
                            }
                        }

                        else
                        {
                            FormsAuthentication.SetAuthCookie(m_UserDetails.UserID.ToString(), true);
                            FormsAuthenticationTicket intellidateTicket = new FormsAuthenticationTicket(1, m_UserDetails.UserID.ToString(), DateTime.Now, DateTime.Now.AddDays(30), true, "");
                            HttpCookie intellidateCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(intellidateTicket));
                            Response.Cookies.Add(intellidateCookie);

                            _AuthenticationResponse.Result = true;
                            if (m_UserDetails.Status == "A")
                            {
                                // Check if any unanswered Criteria questions
                                Criteria[] _UnAnsweredCriteriaQuestions = new Criteria().GetUnAnsweredQuestions(m_UserDetails.UserID);

                                if (_UnAnsweredCriteriaQuestions.Count() == 0)
                                {
                                    _AuthenticationResponse.RedirectPath = "Web/Home";
                                }
                                else
                                {
                                    _AuthenticationResponse.RedirectPath = "Web/Criteria";
                                }
                            }
                            if (m_UserDetails.Status == "P")
                            {
                                _AuthenticationResponse.RedirectPath = "Web/Criteria";
                            }
                            if (m_UserDetails.Status == "I")
                            {
                                _AuthenticationResponse.RedirectPath = "Delete";
                            }
                        }
                    }
                    else if (ACCOUNT_STATUS.ToUpper() == "I")
                    {
                        FormsAuthentication.SetAuthCookie(m_UserDetails.UserID.ToString(), true);
                        FormsAuthenticationTicket intellidateTicket = new FormsAuthenticationTicket(1, m_UserDetails.UserID.ToString(), DateTime.Now, DateTime.Now.AddDays(30), true, "");
                        HttpCookie intellidateCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(intellidateTicket));
                        Response.Cookies.Add(intellidateCookie);

                        _AuthenticationResponse.Result       = true;
                        _AuthenticationResponse.RedirectPath = "Web/ActivateAccount";
                    }
                    else if (ACCOUNT_STATUS.ToUpper() == "D")
                    {
                        _AuthenticationResponse.Result       = false;
                        _AuthenticationResponse.RedirectPath = null;
                    }
                }
            }
            catch (Exception ex)
            {
                IntellidateR1.Error.LogError(ex, "Login LoginUser");
                _AuthenticationResponse.Result = false;
            }
            return(JsonConvert.SerializeObject(_AuthenticationResponse));
        }
Пример #31
0
        public async Task <IActionResult> AuthenticationResponseAsync(string partyId, List <Claim> claims)
        {
            logger.ScopeTrace("Down, OIDC Authentication response.");
            logger.SetScopeProperty("downPartyId", partyId);
            var party = await tenantRepository.GetAsync <TParty>(partyId);

            if (party.Client == null)
            {
                throw new NotSupportedException($"Party Client not configured.");
            }

            var sequenceData = await sequenceLogic.GetSequenceDataAsync <OidcDownSequenceData>(false);

            claims = await claimTransformationsLogic.Transform(party.ClaimTransformations?.ConvertAll(t => (ClaimTransformation)t), claims);

            var authenticationResponse = new AuthenticationResponse
            {
                TokenType = IdentityConstants.TokenTypes.Bearer,
                State     = sequenceData.State,
                ExpiresIn = party.Client.AccessTokenLifetime,
            };
            var sessionResponse = new SessionResponse
            {
                SessionState = claims.FindFirstValue(c => c.Type == JwtClaimTypes.SessionId)
            };

            logger.ScopeTrace($"Response type '{sequenceData.ResponseType}'.");
            var responseTypes = sequenceData.ResponseType.ToSpaceList();

            if (responseTypes.Contains(IdentityConstants.ResponseTypes.Code))
            {
                authenticationResponse.Code = await oauthAuthCodeGrantLogic.CreateAuthCodeGrantAsync(party.Client as TClient, claims, sequenceData.RedirectUri, sequenceData.Scope, sequenceData.Nonce, sequenceData.CodeChallenge, sequenceData.CodeChallengeMethod);
            }

            string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256;

            if (responseTypes.Contains(IdentityConstants.ResponseTypes.Token))
            {
                authenticationResponse.AccessToken = await jwtLogic.CreateAccessTokenAsync(party.Client as TClient, claims, sequenceData.Scope?.ToSpaceList(), algorithm);
            }
            if (responseTypes.Contains(IdentityConstants.ResponseTypes.IdToken))
            {
                authenticationResponse.IdToken = await jwtLogic.CreateIdTokenAsync(party.Client as TClient, claims, sequenceData.Scope?.ToSpaceList(), sequenceData.Nonce, responseTypes, authenticationResponse.Code, authenticationResponse.AccessToken, algorithm);
            }

            logger.ScopeTrace($"Authentication response '{authenticationResponse.ToJsonIndented()}'.");
            var nameValueCollection = authenticationResponse.ToDictionary();

            if (!sessionResponse.SessionState.IsNullOrWhiteSpace())
            {
                logger.ScopeTrace($"Session response '{sessionResponse.ToJsonIndented()}'.");
                nameValueCollection = nameValueCollection.AddToDictionary(sessionResponse);
            }

            logger.ScopeTrace($"Redirect Uri '{sequenceData.RedirectUri}'.");
            logger.ScopeTrace("Down, OIDC Authentication response.", triggerEvent: true);

            var responseMode = GetResponseMode(sequenceData.ResponseMode, sequenceData.ResponseType);
            await sequenceLogic.RemoveSequenceDataAsync <OidcDownSequenceData>();

            await formActionLogic.RemoveFormActionSequenceDataAsync();

            switch (responseMode)
            {
            case IdentityConstants.ResponseModes.FormPost:
                return(await nameValueCollection.ToHtmlPostContentResultAsync(sequenceData.RedirectUri));

            case IdentityConstants.ResponseModes.Query:
                return(await nameValueCollection.ToRedirectResultAsync(sequenceData.RedirectUri));

            case IdentityConstants.ResponseModes.Fragment:
                return(await nameValueCollection.ToFragmentResultAsync(sequenceData.RedirectUri));

            default:
                throw new NotSupportedException();
            }
        }
Пример #32
0
        public ActionResult Index(Login login, string returnUrl)
        {
            //RememberMe default is true
            login.RememberMe = true;

            //Sign user out (if signed in as another user)
            HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            if (ModelState.IsValid)
            {
                var authResponse = new AuthenticationResponse {
                    isSuccess = false
                };

                //Attempt to log in
                var accountAuthenticationServiceClient = new AccountAuthenticationService.AccountAuthenticationServiceClient();

                try
                {
                    //Get the ip address and call origin
                    var ipAddress = Request.UserHostAddress;
                    var origin    = "Web";

                    accountAuthenticationServiceClient.Open();
                    authResponse = accountAuthenticationServiceClient.Authenticate(login.AccountName, login.Email, login.Password, ipAddress, origin, Common.SharedClientKey);

                    //Close the connection
                    WCFManager.CloseConnection(accountAuthenticationServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountAuthenticationServiceClient, exceptionMessage, currentMethodString);

                    // Upate the response object
                    authResponse.isSuccess    = false;
                    authResponse.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                    //auth//response.ErrorMessages[0] = exceptionMessage;

                    #endregion
                }


                //ClaimsIdentity[] claimsIdentity = new ClaimsIdentity[0];
                //claimsIdentity[0] = authResponse.ClaimsIdentity;

                if (authResponse.isSuccess)
                {
                    // Sign User In
                    var currentUtc = new SystemClock().UtcNow;
                    HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                    {
                        IsPersistent = login.RememberMe,
                        ExpiresUtc   = currentUtc.Add(TimeSpan.FromHours(6))
                    },
                                                                       authResponse.ClaimsIdentity);

                    //Store the PlatformUser object as a cookie:
                    AuthenticationCookieManager.SaveAuthenticationCookie(authResponse.AccountUser);

                    //-------------------- Uknown Accounts (Removed)-------

                    /*
                     * string subdomain = Common.GetSubDomain(Request.Url);
                     * if (subdomain.ToLower() == "accounts" || subdomain.ToLower() == "account")
                     * {
                     *  //This is the generic login route....
                     *  //Since the user had to provide the account name, redirect to the new URL
                     *  return Redirect("https://" + authResponse.AccountUser.AccountNameKey + "." + CoreServices.PlatformSettings.Urls.AccountManagementDomain + "/inventory");
                     * }
                     * else */

                    if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        //After user is authenticated, send them to the page they were attempting to use,
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        //otherwise, send them to home:
                        return(RedirectToAction("Index", "Inventory"));
                    }
                }
                else
                {
                    //ModelState.AddModelError("", "Invalid username or password.");

                    //foreach (string error in authResponse.ErrorMessages)
                    //{
                    ModelState.AddModelError("CoreServiceError", authResponse.ErrorMessage);
                    //}


                    //Removed

                    /*
                     * string subdomain = Common.GetSubDomain(Request.Url);
                     * if (subdomain.ToLower() == "accounts" || subdomain.ToLower() == "account")
                     * {
                     *  //This is the generic login route, so we remove the account name and force the user to add it.
                     *  login.AccountName = null;
                     * }*/

                    return(View(login));
                }
            }
            else
            {
                return(View(login));
            }
        }
Пример #33
0
 /// <summary>
 /// This method is not implemented and will always throw a <see cref="NotImplementedException"/>. Use <see cref="RestoreSessionAsync"/>.
 /// </summary>
 /// <param name="response"></param>
 /// <returns></returns>
 public override bool RestoreSession(AuthenticationResponse response)
 {
     throw new NotImplementedException();
 }
        public AuthenticationConclusion AuthenticationUsingAuthorizationCodeFlow(AuthenticationResponse codeResp)
        {
            TokenRequest tokenReq = constructTokenRequest(codeResp);
            TokenResponse tokenResp = callTokenEndpoint(tokenReq);
            if (tokenResp == null)
                return null;

            return conclude(tokenResp);
        }
 internal void Raise(AuthenticationResponse response)
 {
     _authenticationSubject.OnNext(response);
 }
        public TokenRequest constructTokenRequest(AuthenticationResponse codeResp)
        {
            TokenRequest tokenReq = new TokenRequest();
            tokenReq.code = codeResp.code;
            tokenReq.grant_type = "authorization_code";
            tokenReq.redirect_uri = return_uri;
            tokenReq.client_id = client_id;
            tokenReq = pre_send_TokenRequest(tokenReq);
            
            CST_Ops.recordme(this, codeResp, tokenReq);

            return tokenReq;
        }
Пример #37
0
 /// <summary>
 /// Get Authenticated Urls that will be used once the authentication is completed
 /// </summary>
 /// <param name="response"></param>
 private void FillAuthenticatedUrls(AuthenticationResponse response)
 {
     _endpoints.AuthenticatedUrls = response.Links;
 }
 public override SignInIdP_Resp_SignInRP_Req Redir(string dest, ID_Claim claim)
 {
     var AuthCode = claim as AuthorizationCodeEntry;
     if (AuthCode == null)
         return null;
     AuthenticationResponse resp = new AuthenticationResponse();
     resp.code = AuthCode.code;
     HTTP.HTTPComm.HttpPost(dest, "code=" + resp.code);
     return resp;
 }
Пример #39
0
    private void OnLoginError(AuthenticationResponse response)
    {
        Debug.Log("Login error.");

        status = "Login error.";
    }
Пример #40
0
        public AuthenticationResponse Authenticate(string accountName, string email, string password, string ipAddress, string origin, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var authResponse = new AuthenticationResponse();

            #region Refactoring Notes

            /*
             * In scenarios where users are only one to an account we make the account name the "UserName"
             * We can then look up the email address associated with the account (or vice versa depending on if it's an email or username login scenario)
             * This lookup data can be cached in Redis
             *
             */

            #endregion

            var result = AccountSecurityManager.AuthenticateUser(accountName, email, password);

            authResponse.isSuccess    = result.isSuccess;
            authResponse.ErrorMessage = result.ErrorMessage;

            if (result.isSuccess)
            {
                //Get the IdentityUser from the ResponseObject:
                var accountUserIdentity = (AccountUserIdentity)result.ResponseObject;


                //Convert to non Identity version & add to response object:
                authResponse.AccountUser = AccountUserManager.TransformAccountUserIdentityToAccountUser(accountUserIdentity);

                //Get Claims based identity for the user
                System.Security.Claims.ClaimsIdentity identity = AccountUserManager.GetUserClaimsIdentity(
                    accountUserIdentity,
                    DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

                // You can add to claims thusly:
                //identity.AddClaim(new Claim(ClaimTypes.Name, "Name"));

                authResponse.ClaimsIdentity = identity;

                #region Log Account Activity (AuthenticationPassed)

                try
                {
                    var account = AccountManager.GetAccount(authResponse.AccountUser.AccountID.ToString());

                    AccountLogManager.LogActivity(
                        account.AccountID.ToString(),
                        account.StoragePartition,
                        CategoryType.Authentication,
                        ActivityType.Authentication_Passed,
                        "Successfull log in.",
                        authResponse.AccountUser.FirstName + " successfully logged in.",
                        authResponse.AccountUser.Id,
                        authResponse.AccountUser.FirstName,
                        authResponse.AccountUser.Email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }
            else
            {
                #region Log Account Activity (AuthenticationFailed)

                try
                {
                    //var accountId = AccountManager.GetAccountID(accountName);
                    var account = AccountManager.GetAccount(accountName);

                    AccountLogManager.LogActivity(
                        account.AccountID.ToString(),
                        account.StoragePartition,
                        CategoryType.Authentication,
                        ActivityType.Authentication_Failed,
                        "An attempt to log into account '" + accountName + "' with email '" + email + "' has failed.",
                        result.ErrorMessage,
                        "Unknown",
                        "Unknown",
                        email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }


            return(authResponse);
        }
Пример #41
0
 void RegisterCallBack(AuthenticationResponse response)
 {
 }
Пример #42
0
 // Login
 private void OnLoginSuccess(AuthenticationResponse response)
 {
 }
Пример #43
0
        // As client
        private HandshakeResponse sendHandshakeRequest()
        {
            var req = createHandshakeRequest ();
              var res = sendHandshakeRequest (req);
              if (res.IsUnauthorized) {
            _authChallenge = res.AuthChallenge;
            if (_credentials != null && (!_preAuth || _authChallenge.Scheme == "digest")) {
              if (res.Headers.Contains ("Connection", "close")) {
            closeClientResources ();
            setClientStream ();
              }

              var authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
              _nonceCount = authRes.NonceCount;
              req.Headers ["Authorization"] = authRes.ToString ();
              res = sendHandshakeRequest (req);
            }
              }

              return res;
        }
Пример #44
0
 private void OnLoginError(AuthenticationResponse response)
 {
 }
Пример #45
0
    // As client
    private void sendProxyConnectRequest ()
    {
      var req = HttpRequest.CreateConnectRequest (_uri);
      var res = sendHttpRequest (req, 90000);
      if (res.IsProxyAuthenticationRequired) {
        var chal = res.Headers["Proxy-Authenticate"];
        _logger.Warn (
          String.Format ("Received a proxy authentication requirement for '{0}'.", chal));

        if (chal.IsNullOrEmpty ())
          throw new WebSocketException ("No proxy authentication challenge is specified.");

        var authChal = AuthenticationChallenge.Parse (chal);
        if (authChal == null)
          throw new WebSocketException ("An invalid proxy authentication challenge is specified.");

        if (_proxyCredentials != null) {
          if (res.HasConnectionClose) {
            releaseClientResources ();
            _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port);
            _stream = _tcpClient.GetStream ();
          }

          var authRes = new AuthenticationResponse (authChal, _proxyCredentials, 0);
          req.Headers["Proxy-Authorization"] = authRes.ToString ();
          res = sendHttpRequest (req, 15000);
        }

        if (res.IsProxyAuthenticationRequired)
          throw new WebSocketException ("A proxy authentication is required.");
      }

      if (res.StatusCode[0] != '2')
        throw new WebSocketException (
          "The proxy has failed a connection to the requested host and port.");
    }
Пример #46
0
 /// <summary>
 ///
 ///
 /// </summary>
 /// <param name="auth"></param>
 /// <param name="uuidRequest"></param>
 public UserCredentials(AuthenticationResponse auth, UuidByNameResponse uuidRequest)
 {
     this.uuid        = uuidRequest.ID;
     this.name        = auth.PlayerName;
     this.accessToken = auth.AccessToken;
 }
        public AuthenticationResponse Login([FromHeader] BaseHeader header, AuthenRequest authenRequest)
        {
            AuthenticationResponse authenResponse = _accountProcess.LoginProcess(header.Authorization.Substring("Basic".Length).Trim(), authenRequest.AuthenticationInfo, authenRequest.TokenInfo);

            return(authenResponse);
        }
Пример #48
0
        public async Task <AuthenticationResponse> Register(UserRequest user)
        {
            AuthenticationResponse response    = new AuthenticationResponse();
            UserProfile            userProfile = new UserProfile();

            try
            {
                byte[]      pass = security.GetSHA1(user.Email, user.Password);
                UserProfile up   = new UserProfile()
                {
                    Email    = user.Email,
                    Password = pass,
                    Nama     = user.FirstName + " " + user.LastName,
                    Telp     = user.Telp,

                    Created     = DateTime.Now,
                    CreatedBy   = user.Email,
                    RowStatus   = true,
                    IsActivated = user.IsAdminPortal
                };
                UserProfile usr = await dataAccess.GetUserProfileByEmail(user.Email);

                if (usr != null)
                {
                    if (usr.IsActivated == true)
                    {
                        response.IsSuccess = false;
                        response.Message   = "Failed! Email has been registered.";
                    }
                    else
                    {
                        response.IsSuccess = false;
                        response.Message   = "Failed! Email has been registered and Check your email to active your account.";
                    }
                }
                else
                {
                    long id = await dataAccess.Save(up);

                    if (id > 0)
                    {
                        //response.Token = security.GenerateToken(user.Email);
                        response.Message   = "Success created user profile.";
                        response.IsSuccess = true;

                        #region Sent
                        EmailSender emailSender = new EmailSender();

                        #endregion
                    }
                    else
                    {
                        response.IsSuccess = false;
                        response.Message   = "Failed when save userprofile.";
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return(response);
        }
Пример #49
0
 internal virtual void OnAuthenticating(ISession session, AuthenticationResponse respone)
 {
 }
Пример #50
0
        public IViewComponentResult Invoke()
        {
            AuthenticationResponse authReponse = HttpContext.Session.Get <AuthenticationResponse>("AuthenticationResponse");
            List <MenuModel>       menuModel   = new List <MenuModel>();

            foreach (string role in authReponse.Roles)
            {
                if (role == "DB" && menuModel.All(mm => mm.MenuId != 1))
                {
                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 1,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Dashboard,
                        SubMenu    = null,
                        Title      = "Dashboard",
                        Area       = AreaNames.Blank,
                        ImageClass = "flaticon-analytics"
                    });
                }

                if (role == "PIF" && menuModel.All(mm => mm.MenuId != 2))
                {
                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 2,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Persons,
                        SubMenu    = null,
                        Title      = "Basic Information Form",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-information"
                    });
                }

                if (role == "REP" && menuModel.All(mm => mm.MenuId != 26))
                {
                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 26,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Reports,
                        SubMenu    = null,
                        Title      = "Reports",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-network"
                    });
                }

                if ((role == "NOM" || role == "REC") && menuModel.All(mm => mm.MenuId != 3))
                {
                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 3,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Nominations,
                        SubMenu    = null,
                        Title      = "Nominations",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-network"
                    });

                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 25,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Cycle,
                        SubMenu    = null,
                        Title      = "Cycle",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-share"
                    });

                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 15,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.Image,
                        SubMenu    = null,
                        Title      = "Bulk Image Upload",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-user"
                    });

                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 32,
                        Action     = ActionNames.Index,
                        Controller = ControllerNames.SearchPerson,
                        SubMenu    = null,
                        Title      = "Search Person",
                        Area       = AreaNames.Operations,
                        ImageClass = "flaticon-search"
                    });

                    menuModel.Add(new MenuModel
                    {
                        MenuId     = 4,
                        Action     = string.Empty,
                        Controller = string.Empty,
                        SubMenu    = new List <MenuModel> {
                            new MenuModel
                            {
                                MenuId     = 5,
                                Action     = ActionNames.AreaOfStudy,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Area of Study",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 6,
                                Action     = ActionNames.EducationalInstitution,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Educational Institution",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 7,
                                Action     = ActionNames.Country,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Country",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 8,
                                Action     = ActionNames.AkdnTraining,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Akdn Training",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 9,
                                Action     = ActionNames.AreaOfOrigin,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Area Of Origin",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 10,
                                Action     = ActionNames.BusinessNature,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Business Nature",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 11,
                                Action     = ActionNames.BusinessType,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Business Type",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 12,
                                Action     = ActionNames.EducationalDegree,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Educational Degree",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 13,
                                Action     = ActionNames.FieldOfExpertise,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Field of Expertise",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 14,
                                Action     = ActionNames.FieldOfInterest,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Field of Interest",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 16,
                                Action     = ActionNames.Language,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Language",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 17,
                                Action     = ActionNames.MaritalStatus,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Marital Statius",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 18,
                                Action     = ActionNames.Occupation,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Occupation",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 19,
                                Action     = ActionNames.ProfessionalMembership,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Professional Membership",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 20,
                                Action     = ActionNames.PublicServiceInstitution,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Public Service Institution",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 21,
                                Action     = ActionNames.ReligiousQualification,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Religious Qualification",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 22,
                                Action     = ActionNames.Salutation,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Salutation",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 23,
                                Action     = ActionNames.SecularStudyLevel,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Secular Study Level",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 24,
                                Action     = ActionNames.Skill,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Skills",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 26,
                                Action     = ActionNames.City,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "City",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 27,
                                Action     = ActionNames.JamatiTitle,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Jamati Title",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 28,
                                Action     = ActionNames.Position,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Position",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                            new MenuModel
                            {
                                MenuId     = 29,
                                Action     = ActionNames.VoluntaryInstitution,
                                Controller = ControllerNames.LookupCrud,
                                SubMenu    = null,
                                Title      = "Institution",
                                Area       = AreaNames.Administration,
                                ImageClass = "flaticon-network"
                            },
                        },
                        Title      = "Master Data",
                        Area       = string.Empty,
                        ImageClass = "flaticon-list"
                    });
                }
            }

            return(View(menuModel));
        }