Exemplo n.º 1
0
        public IHttpActionResult Post([FromBody] Credentials cred)
        {
            try
            {
                // try to login
                var authData     = AuthenticationRepository.Authenticate(cred.username, cred.password);
                var token        = authData.AccessToken;
                var exp          = authData.ExpiresIn + "";
                var refreshToken = authData.RefreshToken;

                if (token == "")
                {
                    return(this.Unauthorized());
                }

                var userRoles = _personService.GetLoggedInUserRoles(token);
                var user      = _userService.GetByAuthenticationToken(token);
                var p         = _personService.GetLoggedInUserProfile(token);
                var r         = new LoginReturn
                {
                    userToken      = token,
                    userTokenExp   = exp,
                    refreshToken   = refreshToken,
                    userId         = p.ContactId,
                    username       = p.FirstName,
                    userEmail      = p.EmailAddress,
                    roles          = userRoles,
                    age            = p.Age,
                    userPhone      = p.MobilePhone,
                    canImpersonate = user.CanImpersonate
                };


                _loginService.ClearResetToken(cred.username);
                _contactRepository.UpdateUsertoActive(p.ContactId);
                _analyticsService.Track(cred.username, "SignedIn");


                return(this.Ok(r));
            }
            catch (Exception e)
            {
                var apiError = new ApiErrorDto("Login Failed", e);
                throw new HttpResponseException(apiError.HttpResponseMessage);
            }
        }
Exemplo n.º 2
0
        public UserModel ChangePassword(ChangePasswordModel model)
        {
            ActivityLoggingComponent activityLog = new ActivityLoggingComponent();
            UserModel authModel = new UserModel();

            authModel.UserName = model.UserName;
            if (IsUserLoginFirstTime(authModel))
            {
                //first time login create new user with password
                UserModel userModel = new UserModel();
                userModel.UserName              = model.UserName;
                userModel.UserPassword          = model.UserPassword;
                userModel.SecretQuestionID      = model.PasswordQuestionID;
                userModel.SecretQuestionAnswer  = model.PasswordQuesAnswer;
                userModel.IsDeleted             = false;
                userModel.LoginFailAttemptCount = 0;
                userModel.CreatedBy             = model.CreatedBy;
                userModel.LastUpdatedBy         = model.LastUpdatedBy;
                return(CreateNewUser(userModel));
            }
            else
            {
                //change the user password
                using (AuthenticationRepository repo = new AuthenticationRepository())
                {
                    string         cryptoKey     = ConfigurationManager.AppSettings.Get("APSEncryptionKey").ToString();
                    ICryptoLibrary cryptLib      = new CryptoLibrary();
                    string         encrypted_pwd = cryptLib.Encrypt(model.UserPassword, cryptoKey);
                    model.UserPassword = encrypted_pwd;
                    var changePassowrd = repo.ChangeUserPassword(model);
                    if (changePassowrd.UserName != string.Empty)
                    {
                        UserActivityLogModel activityModel = new UserActivityLogModel
                        {
                            User_Name    = changePassowrd.UserName,
                            User_Act_Log = "Change password is successful. Activated User Name is: " + changePassowrd.UserName + ".",
                            CreatedBy    = changePassowrd.UserName,
                            CreatedTime  = DateTime.Now
                        };
                        activityLog.ActivityLog(activityModel);
                    }
                    return(changePassowrd);
                }
            }
        }
Exemplo n.º 3
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("ta:clientAllowedOrigin");
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            string hashedTokenId = HashMd5.GetHash(context.Token);

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                var refreshToken = await _repo.FindRefreshToken(hashedTokenId);

                if (refreshToken != null)
                {
                    //Get protectedTicket from refreshToken class
                    context.DeserializeTicket(refreshToken.ProtectedTicket);
                    var result = await _repo.RemoveRefreshTokenByID(hashedTokenId);
                }
            }
        }
        public async Task Return_Success_OnCall_UserExistsAsync()
        {
            var          _fileLoggerMock = new Mock <IFileLogger>();
            AppDbContext context         = DbHelpers.InitContext("TestDB");

            await context.Users.AddAsync(new LikeButton.Core.Entities.User {
                Email = "*****@*****.**", Username = "******"
            });

            var saved = await context.SaveChangesAsync() > 0;

            Assert.True(saved);
            var command = new AuthenticationRepository(context, _fileLoggerMock.Object);

            var exc = await command.UserExistsAsync("goal");

            Assert.True(exc);
        }
Exemplo n.º 5
0
        /// <summary>
        ///   This function generates new Identity token using refresh token
        /// </summary>
        /// <param name="userRequest"></param>
        /// <param name="context"></param>
        /// <returns>UserResponse</returns>
        public UserResponse SilentAuth(UserRequest userRequest, ILambdaContext context = null)
        {
            AuthenticationRepository authenticationRepository = new AuthenticationRepository();
            UserResponse             userResponse             = new UserResponse();

            try
            {
                userRequest.CognitoClientId = Environment.GetEnvironmentVariable("CognitoClientId").ToString();
                //userRequest.ClientSecret = Environment.GetEnvironmentVariable("ClientSecret").ToString();
                return(authenticationRepository.SilentAuth(userRequest));
            }
            catch (Exception silentAuthException)
            {
                LambdaLogger.Log(silentAuthException.ToString());
                userResponse.Error = ResponseBuilder.InternalError();
                return(userResponse);
            }
        }
Exemplo n.º 6
0
        public UserModel AuthenticateUser(UserModel model)
        {
            string cryptoKey = ConfigurationManager.AppSettings.Get("APSEncryptionKey").ToString();

            if (!string.IsNullOrEmpty(cryptoKey))
            {
                ICryptoLibrary cryptLib = new CryptoLibrary();
                using (AuthenticationRepository repo = new AuthenticationRepository())
                {
                    UserModel userModel = new UserModel();
                    userModel.UserName = model.UserName;
                    userModel          = repo.GetUserDetails(userModel);
                    if (userModel != null)
                    {
                        string decrypted_pwd = cryptLib.Decrypt(userModel.UserPassword, cryptoKey);
                        if (model.UserPassword == decrypted_pwd)
                        {
                            //authentication success
                            userModel.IsAuthenticated = true;
                            return(userModel);
                        }
                        else
                        { //login attempt failed
                            userModel.IsAuthenticated       = false;
                            userModel.LoginFailAttemptCount = userModel.LoginFailAttemptCount + 1;
                            userModel.LastUpdatedBy         = userModel.UserName;
                            userModel = repo.UpdateLoginFailedCount(userModel);
                            return(userModel);
                        }
                    }
                    else
                    {
                        Log.Error("AuthenticateUser: No User info available in DB for this user: "******"AuthenticateUser: APSEncryptionKey is empty");
                return(null);
            }
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            //Get the client ID from the Ticket properties
            var clientid = context.Ticket.Properties.Dictionary["client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

            //Generating a Uniqure Refresh Token ID
            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                // Getting the Refesh Token Life Time From the Owin Context
                var refreshTokenLifeTime = context.OwinContext.Get <string>("ta:clientRefreshTokenLifeTime");

                //Creating the Refresh Token object
                var token = new RefreshToken()
                {
                    //storing the RefreshTokenId in hash format
                    ID          = Helper.GetHash(refreshTokenId),
                    ClientID    = clientid,
                    UserName    = context.Ticket.Identity.Name,
                    IssuedTime  = DateTime.Now,
                    ExpiredTime = DateTime.Now.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };

                //Setting the Issued and Expired time of the Refresh Token
                context.Ticket.Properties.IssuedUtc  = token.IssuedTime;
                context.Ticket.Properties.ExpiresUtc = token.ExpiredTime;

                token.ProtectedTicket = context.SerializeTicket();

                var result = _repo.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
Exemplo n.º 8
0
        public async static Task Main(string[] args)
        {
            Console.WriteLine("Comenzó Generador de Data!");
            connection             = new SqlConnection(connectionString);
            nivelRepository        = new NivelRepository(connection);
            lineaCarreraRepository = new LineaCarreraRepository(connection);
            var conocimientoRepository = new ConocimientoRepository(connection);

            participanteRepository = new ParticipanteRepository(connection);
            ratingCursoRepository  = new RatingCursoRepository(connection);
            var authenticationRepository = new AuthenticationRepository(connection);

            cursoRepository = new CursoRepository(connection);

            var myProfile           = new AutoMapperProfiles();
            var configuration       = new MapperConfiguration(cfg => cfg.AddProfile(myProfile));
            var mapper              = new Mapper(configuration);
            var participanteService = new ParticipanteService(participanteRepository, conocimientoRepository, mapper, null);

            _authService = new AuthenticationService(authenticationRepository, participanteService, mapper);

            try
            {
                _faker = new ParticipanteFaker();

                await GenerarEscaladores();
                await GenerarSherpas();
                await GenerarAdmin();
                await GenerarCursoImagenes();

                for (int i = 0; i < 3; i++)
                {
                    await GenerarRatingCursosAleatorios();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Excepción: " + ex.Message);
            }
            Console.WriteLine("Finalizó Generador Data!");
            Console.ReadLine();
        }
Exemplo n.º 9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "username", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
        public override async Task Authenticated(DiscordAuthenticatedContext context)
        {
            if (context.Verified)
            {
                var authenticationRepository = new AuthenticationRepository();
                var user = await authenticationRepository.FindUserAsync(context.Email);

                if (user == null) //if user is unknown create him in the system.
                {
                    await authenticationRepository.RegisterUserAsync(new UserViewModel
                    {
                        UserName = context.Email,
                        Password = Guid.NewGuid().ToString("N")
                    });
                }
            }
            context.Properties.Dictionary.Add("userName", context.Email);
            context.OwinContext.Set("discord:verified", context.Verified);
            await base.Authenticated(context);
        }
        public async Task Return_Success_OnCall_LoginAsync()
        {
            var          _fileLoggerMock = new Mock <IFileLogger>();
            AppDbContext context         = DbHelpers.InitContext("TestDB");
            var          command         = new AuthenticationRepository(context, _fileLoggerMock.Object);

            var res = await command.RegisterAsync(new LikeButton.Core.DTOs.APIRequest.CreateUserAPIRequest {
                Email    = "*****@*****.**",
                username = "******", password = "******"
            });



            var exc = await command.LoginAsync(new LikeButton.Core.DTOs.APIRequest.UserLoginRequest {
                username = "******", password = "******"
            });

            Assert.NotNull(exc);
            Assert.IsType <UserSuccessLoginResponse>(exc);
        }
Exemplo n.º 12
0
        public UserModel CreateNewUser(UserModel model)
        {
            ActivityLoggingComponent activityLog = new ActivityLoggingComponent();
            string cryptoKey = ConfigurationManager.AppSettings.Get("APSEncryptionKey").ToString();

            if (!string.IsNullOrEmpty(cryptoKey))
            {
                ICryptoLibrary cryptLib      = new CryptoLibrary();
                string         encrypted_pwd = cryptLib.Encrypt(model.UserPassword, cryptoKey);
                model.UserPassword = encrypted_pwd;
                using (AuthenticationRepository repo = new AuthenticationRepository())
                {
                    var userCreation = repo.CreateNewUser(model);
                    if (userCreation.UserID > 0)
                    {
                        UserActivityLogModel activityModel = new UserActivityLogModel
                        {
                            User_Name    = userCreation.UserName,
                            User_Act_Log = "User creation successful. Newly created User Name is: " + userCreation.UserName + ".",
                            CreatedBy    = userCreation.CreatedBy,
                            CreatedTime  = DateTime.Now
                        };
                        activityLog.ActivityLog(activityModel);
                    }
                    return(userCreation);
                }
            }
            else
            {
                UserActivityLogModel activityModel = new UserActivityLogModel
                {
                    User_Name    = model.UserName,
                    User_Act_Log = "Error occurred! User creation was unsuccessful for : " + model.UserName + ".",
                    CreatedBy    = model.CreatedBy,
                    CreatedTime  = DateTime.Now
                };
                activityLog.ActivityLog(activityModel);
                throw new Exception();
            }
        }
Exemplo n.º 13
0
        public IHttpActionResult RemovePinFromMap([FromBody] int participantId)
        {
            return(Authorized(token =>
            {
                try
                {
                    _finderService.DisablePin(participantId);
                    _awsCloudsearchService.DeleteSingleConnectRecordInAwsCloudsearch(participantId, 1);

                    // Call  analytics
                    _analyticsService.Track(AuthenticationRepository.GetContactId(token).ToString(), "RemovedFromMap");

                    return Ok();
                }
                catch (Exception e)
                {
                    _logger.Error("Could not create pin", e);
                    var apiError = new ApiErrorDto("Remove pin from map failed", e);
                    throw new HttpResponseException(apiError.HttpResponseMessage);
                }
            }));
        }
Exemplo n.º 14
0
 public OrgManUnitOfWork(OrgManEntities context = null)
 {
     _context                                = context ?? new OrgManEntities();
     AdressRepository                        = new AdressRepository(_context);
     CommunicationTypeRepository             = new CommunicationTypeRepository(_context);
     CountryRepository                       = new CountryRepository(_context);
     LoginRepository                         = new LoginRepository(_context);
     MandatorRepository                      = new MandatorRepository(_context);
     PersonToMandatorRepository              = new GenericRepository <PersonToMandator>(_context);
     MeetingRepository                       = new MeetingRepository(_context);
     MemberInformationRepository             = new MemberInformationRepository(_context);
     MemberInformationToMembershipRepository = new MemberInformationToMembershipRepository(_context);
     MembershipRepository                    = new MembershipRepository(_context);
     PhoneRepository                         = new PhoneRepository(_context);
     EmailRepository                         = new EmailRepository(_context);
     SalutationRepository                    = new SalutationRepository(_context);
     IndividualPersonRepository              = new IndividualPersonRepository(_context);
     SystemPersonRepository                  = new GenericRepository <SystemPerson>(_context);
     PersonRepository                        = new GenericRepository <Person>(_context);
     AuthenticationRepository                = new AuthenticationRepository(_context);
     SessionRepository                       = new GenericRepository <Session>(_context);
 }
Exemplo n.º 15
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                var refreshTokenLifeSpan = context.OwinContext.Get <string>("clientRefreshTokenLifeSpan");

                var token = new OpenAPIRefreshToken()
                {
                    Id         = Hasher.GetHash(refreshTokenId),
                    ClientId   = clientid,
                    Subject    = context.Ticket.Identity.Name,
                    IssuedUTC  = DateTime.UtcNow,
                    ExpiresUTC = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeSpan))
                };

                context.Ticket.Properties.IssuedUtc  = token.IssuedUTC;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUTC;

                token.Protected_Ticket = context.SerializeTicket();

                var result = await _repo.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
Exemplo n.º 16
0
        // private  DbContextOptions<RalDbContext> _options;

        public RalUnitOfWork(RalDbContext dbContext)
        {
            _dbContext          = dbContext;
            BusinessPartners    = new BusinessPartnerRepository(dbContext);
            Company             = new CompanyRepository(dbContext);
            Employees           = new EmployeesRepository(dbContext);
            Quotations          = new DocumentRepository <QuotationEntity, QuotationHeaderEntity>(dbContext);
            Orders              = new DocumentRepository <OrderEntity, OrderHeaderEntity>(dbContext);
            DeliveryNotes       = new DocumentRepository <DeliveryNoteEntity, DeliveryNoteHeaderEntity>(dbContext);
            Invoices            = new DocumentRepository <InvoiceEntity, InvoiceHeaderEntity>(dbContext);
            CreditNotes         = new DocumentRepository <CreditNoteEntity, CreditNoteHeaderEntity>(dbContext);
            DownPaymentRequests = new DocumentRepository <DownPaymentRequest, DownPaymentRequestHeader>(dbContext);

            Salesmen           = new SalesmanRepository(dbContext);
            ProductGroups      = new ProductGroupRepository(dbContext);
            Products           = new ProductRepository(dbContext);
            RefreshTokens      = new AuthenticationRepository(dbContext);
            IdentityUsers      = new IdentityUserRepository(dbContext);
            UserLocations      = new UserLocationRepository(dbContext);
            LeadUsersData      = new LeadUserDataRepository(dbContext);
            EmployeeTimeClocks = new EmployeeTimeClockRepository(dbContext);
            Activities         = new ActivityRepository(dbContext);
            Attachments        = new AttachmentRepository(dbContext);
        }
Exemplo n.º 17
0
        public IHttpActionResult InviteToGroup([FromUri] int groupId, [FromUri] string finderFlag, [FromBody] User person)
        {
            if (!ModelState.IsValid)
            {
                var errors    = ModelState.Values.SelectMany(val => val.Errors).Aggregate("", (current, err) => current + err.Exception.Message);
                var dataError = new ApiErrorDto("CreateInvitation Data Invalid", new InvalidOperationException("Invalid CreateInvitation Data " + errors));
                throw new HttpResponseException(dataError.HttpResponseMessage);
            }

            return(Authorized(token =>
            {
                try
                {
                    _finderService.InviteToGroup(token, groupId, person, finderFlag);

                    // Call Analytics
                    var props = new EventProperties {
                        { "InvitationToEmail", person.email }
                    };
                    _analyticsService.Track(AuthenticationRepository.GetContactId(token).ToString(), "HostInvitationSent", props);

                    return (Ok());
                }
                catch (ValidationException e)
                {
                    var error = new ApiErrorDto("Not authorized to send invitations of this type", e, HttpStatusCode.Forbidden);
                    throw new HttpResponseException(error.HttpResponseMessage);
                }
                catch (Exception e)
                {
                    _logger.Error($"Could not create invitation to recipient {person.firstName + " " + person.lastName} ({person.email}) for group {3}", e);
                    var apiError = new ApiErrorDto("CreateInvitation Failed", e, HttpStatusCode.InternalServerError);
                    throw new HttpResponseException(apiError.HttpResponseMessage);
                }
            }));
        }
Exemplo n.º 18
0
        public void ShouldCreatePageRecord()
        {
            var uid      = USERNAME;
            var pwd      = PASSWORD;
            var authData = AuthenticationRepository.authenticate(uid, pwd);
            var token    = authData["token"].ToString();
            var recordId = _fixture.GetContactId(token);

            var householdDict = new Dictionary <string, object>
            {
                { "Contact_ID", recordId },
                { "Congregation_ID", 5 },
                { "Household_Name", "API Household" }
            };
            var hhPageId = Convert.ToInt32(ConfigurationManager.AppSettings["MyHousehold"]);

            var newRecordId = MinistryPlatformService.CreateRecord(hhPageId, householdDict, token);

            Assert.IsNotNull(newRecordId);
            Assert.AreNotEqual(0, newRecordId);

            //TODO: Determine how to clean up after tests
            //MinistryPlatformService.DeleteRecord(hhPageId, newRecordId, null, adminToken);
        }
Exemplo n.º 19
0
        public void AsignarCita()
        {
            ISchedulingPetitionsRepository petRepository  = new SchedulingPetitionsRepository();
            SchedulingPetitionsService     petService     = new SchedulingPetitionsService();
            IAuthenticationRepository      authRepository = new AuthenticationRepository();
            AuthenticationService          authService    = new AuthenticationService();
            string token = authService.RefreshToken(authRepository, "3194198375", "CC79880800", "alvaroposada");
            Dictionary <string, string> values = new Dictionary <string, string>()
            {
                { "espacioCita", "10782925" },
                { "tipoId", "CC" },
                { "numId", "79880800" },
                { "centroMedico", "55983" },
                { "medico", "2355" },
                { "especialidad", "172" },
                { "telefono", "000" },
                { "correo", "" },
                { "celular", "3134846707" },
                { "token", token }
            };
            string res = petService.AsignarCita(petRepository, values, "alvaroprueba");

            Assert.IsNotNull(res);
        }
Exemplo n.º 20
0
 public static Dictionary <string, object> Login(string username, string password)
 {
     return(AuthenticationRepository.authenticate(username, password));
 }
 public AdUserGroupSynchronizer(ILogger <Deauthentication> logger, UserRepository userRepository, AuthenticationRepository authenticationRepository, int organizaionCode, Domain domain, IEnumerable <IActiveDirectorySynchronizable> dbs, IEnumerable <ILdap> ldaps) : base(logger, userRepository, authenticationRepository, organizaionCode, dbs, ldaps)
 {
     this._domain = domain;
 }
Exemplo n.º 22
0
 public FaceBookLoginController()
 {
     this._authenticationRepository = new AuthenticationRepository();
 }
        //*********The Following Method can be used if Authentication take place from custom users Table***********//
        public Boolean ValidateUser(string Username, string password, string UserLanguage, ref bool locked, ref string Msg)
        {
            Boolean status = false;

            using (BaseRepository baseRepo = new BaseRepository())
            {
                // BizContext bc = new BizContext();

                Business.BizTbl_User user = BizUser.GetUser(baseRepo.BizDB, string.Empty, Username, password);
                BizContext BizContext = new BizContext();
                // BizContext bc = new BizContext();
                UserContext uc = new UserContext();
                // BizApplication.GetBizContext(Username, password, CultureCode,ref bc);
                if (user != null)
                {
                    status = true;
                    BizApplication.SetUserContext(baseRepo.BizDB, ref uc, Convert.ToInt64(user.ID), CultureCode);
                    BizContext.UserContext = uc;

                        //if (uc.IsHotelAdmin()) {
                        //    System.Linq.IQueryable<Business.TB_Hotel> userHotels = BizHotel.GetHotels(baseRepo.BizDB, null, uc.FirmID, null, user.ID.ToString());
                        //    foreach (Business.TB_Hotel hotel in userHotels)
                        //    {
                        //        BizContext.Hotels.Add(hotel.ID, hotel.Name);
                        //    }
                        //    Business.TB_Hotel userHotel = userHotels.First();
                        //    BizContext.HotelID = userHotel.ID;
                        //    BizContext.HotelCountryID = userHotel.CountryID;
                        //    BizContext.HotelRegionID = Convert.ToInt64(userHotel.RegionID);
                        //    BizContext.HotelCityID = Convert.ToInt64(userHotel.CityID);
                        //    BizContext.HotelCurrencyID = Convert.ToString(userHotel.CurrencyID);
                        //   // BizContext.HotelCurrencyName = dc.GetColumn(GetCurrencies(dc, CultureCode, bc.HotelCurrencyID)(0), "Name");
                        //    BizContext.HotelAccommodationTypeID = userHotel.HotelAccommodationTypeID;
                        //    BizContext.HotelAvailabilityRateUpdate = Convert.ToBoolean(userHotel.AvailabilityRateUpdate);
                        //    BizContext.HotelRoutingName = userHotel.RoutingName;
                        //    BizContext.FirmID = Convert.ToString(userHotel.FirmID);
                        //    Session["SelectedHotelID"] = userHotel.ID;
                        //    Session["SelectedHotelName"] = userHotel.Name;
                        //}

                    if (BizContext.UserContext.IsHotelAdmin())
                    {

                       // System.Linq.IQueryable<Business.TB_Hotel> userHotels = BizHotel.GetHotels(baseRepo.BizDB, null, uc.FirmID, null, user.ID.ToString());
                        int i = 0;
                        baseRepo.SQLCon.Open();
                        DataTable dt = new DataTable();
                        SqlCommand cmd = new SqlCommand("B_Ex_GetUserHotelByUserID_TB_Hotel_SP", baseRepo.SQLCon);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@UserID", user.ID.ToString());
                        cmd.Parameters.AddWithValue("@FirmID", uc.FirmID);
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        baseRepo.SQLCon.Close();
                        foreach (DataRow hotel in dt.Rows)
                        {
                            BizContext.Hotels.Add(Convert.ToInt32(hotel["ID"]), (hotel["Name"].ToString()));
                            if (i == 0)
                            {
                                BizContext.HotelID = Convert.ToInt32(hotel["ID"]);
                                BizContext.FirmID = hotel["FirmID"].ToString();
                                BizContext.HotelAccommodationTypeID = Convert.ToInt32(hotel["HotelAccommodationTypeID"]);
                                BizContext.HotelRoutingName = hotel["Name"].ToString();
                                Session["SelectedHotelID"] = Convert.ToInt32(hotel["ID"]);
                                Session["SelectedHotelName"] = hotel["Name"].ToString();
                            }
                            i++;
                        }
                    }
                    int userCountryID = 0;
                    //if (bc.UserContext.IPAddress == string.Empty)
                    //{
                    if (Session["GBAdminBizContext"] != null)
                    {
                        BizContext = (BizContext)Session["GBAdminBizContext"];
                    }
                    Session["GBAdminBizContext"] = BizContext;

                    if (UserLanguage != "")
                    {
                        try
                        {
                            string[] words = UserLanguage.Split(',');

                            BizContext.SystemCultureCode = words[1];
                            BizContext.CultureCode = words[0];
                            Session["CultureCode"] = words[0];
                            Session["GBAdminBizContext"] = BizContext;
                        }
                        catch
                        {
                            BizContext.SystemCultureCode = "en-GB";
                            BizContext.CultureCode = "en";
                            Session["GBAdminBizContext"] = BizContext;
                            Session["CultureCode"] = "en";
                        }

                    }
                    else
                    {
                        BizContext.SystemCultureCode = "en-GB";
                        BizContext.CultureCode = "en";
                        Session["GBAdminBizContext"] = BizContext;
                        Session["CultureCode"] = "en";
                    }

                    string userIpAddress = GetUserIPAddress();
                    //GetCultureByIpaddress(userIpAddress);
                    try
                    {
                        CountriesRepository countryRepo = new CountriesRepository();
                        Business.TB_Country userCountryInfo = BizApplication.GetCountryInfoFromIPAddress(baseRepo.BizDB, userIpAddress);

                        userCountryID = userCountryInfo.ID;
                    }
                    catch
                    {
                        userCountryID = 0;
                    }

                    // bc.UserContext.IPAddress = userIpAddress;
                    // }

                    //if (bc.UserSessionID == string.Empty)
                    //{
                    AuthenticationRepository authRepo = new AuthenticationRepository();
                    string countryID = (userCountryID == 0 ? String.Empty : userCountryID.ToString());
                    string UserSessionID = BizUser.SaveUserSession(baseRepo.BizDB, String.Empty, Guid.NewGuid().ToString(), user.ID.ToString(), countryID, userIpAddress, DateTime.Now.ToString()).ToString();
                    //}

                    if (Session["GBAdminBizContext"] != null)
                    {
                        BizContext = (BizContext)Session["GBAdminBizContext"];
                    }
                    BizContext.UserSessionID = UserSessionID;
                    Session["GBAdminBizContext"] = BizContext;

                    // Session[BizCommon.AdminBizContextName] = bc;
                    BizUser.AddUserOperation(baseRepo.BizDB, user.ID.ToString(), DateTime.Now.ToString(), BizCommon.Operation.Login, "", "", GetUserIPAddress(), UserSessionID);

                    Session["username"] = user.DisplayName;
                    Session["UserID"] = user.ID;
                }
                else
                {
                    Msg = Resources.Resources.CheckYourUserNameAndPasswordWarning; //BizMessage.GetMessage(baseRepo.BizDB, "CheckYourUserNameAndPasswordWarning", "en");
                }
            }

            return status;
        }
Exemplo n.º 24
0
 public ClientsController()
 {
     _AuthRepo = new AuthenticationRepository();
 }
Exemplo n.º 25
0
 protected AdSynchronizerBase(ILogger <Deauthentication> logger, UserRepository userRepository, AuthenticationRepository authenticationRepository, int organizaionCode, IEnumerable <IActiveDirectorySynchronizable> dbs, IEnumerable <ILdap> ldaps)
 {
     Logger = logger;
     this.UserRepository           = userRepository;
     this.AuthenticationRepository = authenticationRepository;
     this.OrganizaionCode          = organizaionCode;
     this.Dbs   = dbs;
     this.Ldaps = ldaps;
 }
Exemplo n.º 26
0
 public void Repository()
 {
     IAuthenticationRepository a = new AuthenticationRepository();
     var f=a.Find(null);
 }
Exemplo n.º 27
0
 public GoogleLoginController()
 {
     this._authenticationRepository = new AuthenticationRepository();
 }
 public void Initialize()
 {
     var authenticationRepository = new AuthenticationRepository();
     var isAuth = authenticationRepository.Login("*****@*****.**", "12345678");
 }
Exemplo n.º 29
0
 public void Repository()
 {
     IAuthenticationRepository a = new AuthenticationRepository();
     var f = a.Find(null);
 }
Exemplo n.º 30
0
 public Users Check(Users item)
 {
     return(AuthenticationRepository.Check(item));
 }
Exemplo n.º 31
0
 /// <summary>
 /// Initializes a new account controller
 /// </summary>
 public AccountController()
 {
     authenticationRepository = new AuthenticationRepository();
 }
Exemplo n.º 32
0
        public AccountController()
        {
            var userManager = UserManager.Create();

            _repo = new AuthenticationRepository(userManager);
        }