示例#1
0
        public ActionResult CreateClientUser(ClientUserModel vm)
        {
            var list = _context.tblUserRoleAssigns.Where(x => x.ClientId == vm.ClientId);

            if (list != null)
            {
                _context.tblUserRoleAssigns.RemoveRange(list);
                _context.SaveChanges();
            }

            if (vm.UserSelected != null)
            {
                foreach (var user in vm.UserSelected)
                {
                    int userId     = Convert.ToInt16(user);
                    var roleassign = new tblUserRoleAssign();
                    roleassign.ClientId     = vm.ClientId;
                    roleassign.AssignUserId = userId;
                    roleassign.TaskId       = 0;
                    roleassign.ProjectId    = 0;
                    _context.tblUserRoleAssigns.Add(roleassign);
                    _context.SaveChanges();
                }
            }
            return(RedirectToAction("Index", new { area = "Client" }));
        }
示例#2
0
        /// <summary>
        /// Método para encontrar um usuário pelo username. Não está implementado corretamente ainda.
        /// </summary>
        /// <param name="username">Nome de usuário a ser retornado</param>
        /// <returns>Usuário com o username especificado.</returns>
        private async Task <ClientUserModel> GetUser(string username)
        {
            string          connectionString = @"Server=10.49.16.23\SME_PRD;Database=GestaoPedagogica;User Id=Caique.Santos;Password=Antares2014;";
            ClientUserModel clientUser       = null;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("API_SMECORE_GET_USER_INFO", con);
                    cmd.Parameters.Add(new SqlParameter("@usu_login", username));
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    SqlDataReader reader;

                    con.Open();
                    reader = cmd.ExecuteReader();
                    reader.Read();

                    clientUser = new ClientUserModel()
                    {
                        Username = username
                    };
                    clientUser.Name  = reader["nome"].ToString();
                    clientUser.Email = reader["email"].ToString();
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }

            return(clientUser);
        }
示例#3
0
        public override object ToJson()
        {
            var json = new ClientUserModel(GetConcretEntity <User>(), UserInfo)
            {
                RoleImageUrl = RoleVM.ImageVM.StaticImageFile,
                icon         = ImageVM.StaticImageFile,
            };

            if (RoomWindowVM != null)
            {
                json.CanSendGift          = HasCommand(RoomWindowVM.RoomVM.Id, Applications._9258App.FrontendCommands.SendGiftCommandId, -1);
                json.CanReceiveGift       = HasCommand(RoomWindowVM.RoomVM.Id, Applications._9258App.FrontendCommands.ReceiveGiftCommandId, -1);
                json.CanSendHornMsg       = HasCommand(RoomWindowVM.RoomVM.Id, Applications._9258App.FrontendCommands.HornCommandId, -1);
                json.CanSendHallHornMsg   = HasCommand(RoomWindowVM.RoomVM.Id, Applications._9258App.FrontendCommands.HallHornCommandId, -1);
                json.CanSendGlobalHornMsg = HasCommand(RoomWindowVM.RoomVM.Id, Applications._9258App.FrontendCommands.GlobalHornCommandId, -1);
                json.IsOnMic = MicStatus != MicStatusMessage.MicStatus_Off;
            }
            if (json.IsOnMic)
            {
                json.CameraImageUrl = ApplicationVM.OnMicImageUrl;
            }
            else
            {
                json.CameraImageUrl = ApplicationVM.DownMicImageUrl;
            }
            return(json);
        }
示例#4
0
        public ActionResult ViewClientUser(int id)
        {
            ClientUserModel vm = new ClientUserModel();

            vm.ClientId = id;
            vm.AllUsers = new SelectList((from user in _context.tblUsers
                                          join role in _context.tblRoles on user.RoleId equals role.RoleId
                                          where role.RoleId == 1 || role.RoleId == 3
                                          select new { UserId = user.UserId.ToString(), user.FullName, role.RoleDesc }).ToList(), "UserId", "FullName", "RoleDesc ", 0);

            vm.UserSelected = _context.tblUserRoleAssigns.Where(x => x.ClientId == id).ToList().Select(e => e.AssignUserId.ToString().Trim()).ToArray();
            return(PartialView("_AddClientUser", vm));
        }
示例#5
0
        private ClientUserModel GetClientUserModel(int userId)
        {
            ClientUserModel model = new ClientUserModel();
            SysClientUser   user  = CurrentDb.SysClientUser.Where(m => m.Id == userId).FirstOrDefault();

            model.Id                = user.Id;
            model.UserName          = user.UserName;
            model.PhoneNumber       = user.PhoneNumber;
            model.Email             = user.Email;
            model.FirstName         = user.FirstName;
            model.LastName          = user.LastName;
            model.FavoriteColors    = user.FavoriteColors;
            model.FavoriteRetailers = user.FavoriteRetailers;

            return(model);
        }
        public async Task <IActionResult> Update([FromRoute] Guid id, [FromBody] ClientUserModel model)
        {
            try
            {
                var response = await _service.Update(model);

                if (!response.IsSuccessful)
                {
                    return(BadRequest(response));
                }
                return(Ok(response));
            }
            catch
            {
                return(StatusCode(500, "Internal Server Error."));
            }
        }
示例#7
0
        public async Task <ActionResult <string> > LoginIdentity([FromBody] CredentialModel credential)
        {
            if (!Data.Business.Authentication.ValidateUser(credential.Username, credential.Password))
            {
                // Executa o método de autenticação pelo CoreSSO.Identity (sistema legado)
                ClientUserModel user = await Authenticate(credential);

                if (user != null)
                {
                    user.SMEToken              = new SMETokenModel();
                    user.SMEToken.Token        = CreateToken(user);                                                                       // Cria o token de acesso
                    user.SMEToken.Session      = Data.Functionalities.Cryptography.CreateHashKey();                                       // Cria a sessão
                    user.SMEToken.RefreshToken = Data.Functionalities.Cryptography.CreateHashKey();                                       // Cria o refresh token
                    await Data.Business.Authentication.RegisterUser(credential.Username, credential.Password);                            // Cadastra o usuário dentro do banco PostgreSQL (Novo SGP)

                    await Data.Business.Authentication.LoginUser(credential.Username, user.SMEToken.Session, user.SMEToken.RefreshToken); // Loga o usuário no sistema

                    return(Ok(user));
                }
            }
            else
            {
                string session      = Data.Functionalities.Cryptography.CreateHashKey();                  // Cria a sessão
                string refreshToken = Data.Functionalities.Cryptography.CreateHashKey();                  // Cria o refresh token

                await Data.Business.Authentication.LoginUser(credential.Username, session, refreshToken); // Loga o usuário no sistema

                return(Ok(new
                {
                    Token = CreateToken(credential.Username),
                    Session = session,
                    RefreshToken = refreshToken
                }));
            }

            return(Unauthorized());
        }
示例#8
0
        /// <summary>
        /// Método para validar as credenciais de login do usuário.
        /// </summary>
        /// <param name="credential">Objeto que contém informações da credencial do usuário</param>
        /// <returns>Objeto contendo informações do usuário encontrado, caso não seja encontrado nenhum usuário com correspondente a credencial enviada o método retorna nulo.</returns>
        private async Task <ClientUserModel> Authenticate(CredentialModel credential)
        {
            // Configurações iniciais
            string            url     = "http://identity.sme.prefeitura.sp.gov.br/Account/Login";
            CookieContainer   cookies = new CookieContainer();
            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookies;

            // Inicialização do cliente para requisições (GET e POST)
            using (HttpClient client = new HttpClient(handler))
                using (HttpResponseMessage getResponse = await client.GetAsync(url))
                    using (HttpContent content = getResponse.Content)
                    {
                        // Extrai o anti forgery token da pagina da requisição GET
                        string result = await content.ReadAsStringAsync();

                        string forgeryToken = ExtractDataByName(result, "__RequestVerificationToken");

                        // Faz o POST dos dados (login) caso o usuário não esteja logado
                        if (forgeryToken != string.Empty)
                        {
                            // Cria os dados necessários que compõe o corpo da requisição
                            Dictionary <string, string> data = new Dictionary <string, string>();
                            data.Add("__RequestVerificationToken", forgeryToken); // Adiciona o Anti Forgery Token
                            data.Add("Username", credential.Username);            // Adiciona o nome de usuário
                            data.Add("Password", credential.Password);            // Adiciona a senha
                            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
                            {
                                Content = new FormUrlEncodedContent(data)
                            };                                                                  // Encoda os dados no formato correto dentro da requisição
                            HttpResponseMessage postResponse = await client.SendAsync(request); // Executa a requisição

                            // Caso a requisição não ocorra corretamente, retorna 'null'
                            if (!postResponse.IsSuccessStatusCode)
                            {
                                return(null);
                            }

                            result = await postResponse.Content.ReadAsStringAsync();

                            // Caso o usuário não seja autenticado, retorna 'null'
                            if (result.StartsWith("<form method='post' action='http://coresso.sme.prefeitura.sp.gov.br/Login.ashx'>") == false)
                            {
                                return(null);
                            }
                        }

                        // Cria e pega informações do usuário
                        ClientUserModel user = await GetUser(credential.Username);

                        if (user == null)
                        {
                            user = new ClientUserModel()
                            {
                                Username = credential.Username
                            }
                        }
                        ;

                        // Pega os cookies da pagina
                        user.Cookies = cookies.GetCookies(new Uri(url)).Cast <Cookie>();

                        // Preenche as informações do identity
                        user.Identity              = new IdentityModel();
                        user.Identity.code         = ExtractDataByName(result, "code");
                        user.Identity.id_token     = ExtractDataByName(result, "id_token");
                        user.Identity.access_token = ExtractDataByName(result, "access_token");
                        user.Identity.token_type   = ExtractDataByName(result, "token_type");
                        user.Identity.expires_in   = ExtractDataByName(result, "expires_in");
                        user.Identity.scope        = ExtractDataByName(result, "scope");
                        user.Identity.state        = ExtractDataByName(result, "state");
                        user.Identity.sesion_state = ExtractDataByName(result, "session_state");

                        return(user);
                    }
        }
示例#9
0
 /// <summary>
 /// Método para gerar o token de acesso.
 /// </summary>
 /// <param name="user">Objeto contendo informações do usuário</param>
 /// <returns>Token gerado à partir das informações do usuário.</returns>
 private string CreateToken(ClientUserModel user)
 {
     return(CreateToken(user.Username));
 }
示例#10
0
        // GET: Order
        public ActionResult createOrder()
        {
            // Null handling
            if (Session["loggedInState"] == null)
            {
                return(Redirect("/403.html"));
            }

            // Checks if logged in
            bool state = (bool)Session["loggedInState"];

            if (state == true)
            {
                // Creates handlers for order creating
                GoodsHandler         goodsHand   = new GoodsHandler();
                SpecificationHandler specHand    = new SpecificationHandler();
                PackageHandler       packHand    = new PackageHandler();
                TransactionHandler   tranHandler = new TransactionHandler();

                // Necessary models
                ClientUserModel cuModel    = new ClientUserModel();
                OrderModel      orderModel = new OrderModel();

                // Stored details for package specification
                int weight = int.Parse(Request.Form["weight"]);
                int height = int.Parse(Request.Form["height"]);
                int length = int.Parse(Request.Form["length"]);
                int width  = int.Parse(Request.Form["width"]);

                // Stored details for package
                String name     = Request.Form["goodsDescriptor"];
                String handling = Request.Form["options"];


                String deliveryType = Request.Form["deliveryBands"];

                // Stored details for order
                int deliveryBand = 0;

                switch (deliveryType)
                {
                case "Next Day Delivery":
                    deliveryBand = 1;
                    break;

                case "Express 1-2 Days":
                    deliveryBand = 2;
                    break;

                case "Standard 3-5 Days":
                    deliveryBand = 3;
                    break;

                case "Basic 5-10 Days":
                    deliveryBand = 4;
                    break;
                }


                // Holds the order objects
                Order newOrder = new Order();

                // Creates the foreign objects, and gets the IDs
                int goodsID = goodsHand.create(name, handling);
                int specID  = specHand.create(weight, height, length, width);
                int packID  = packHand.create(goodsID, specID);

                // Acquires client data
                ClientUser thisUser = cuModel.SearchClientUser(int.Parse(Session["userID"].ToString()));

                // Acquires account type (Standard | Premium)
                AccountModel accModel    = new AccountModel();
                Account      thisAccount = accModel.SearchAccount(thisUser.AccountID);
                int          accountType = thisAccount.AccountTypeID;

                // Sets up the order
                newOrder.AccountID            = thisUser.AccountID;
                newOrder.DestinationAddressID = int.Parse(Request.Form["address1"]);
                newOrder.SourceAddressID      = int.Parse(Request.Form["address2"]);
                newOrder.Placed      = DateTime.Now;
                newOrder.OrderStatus = "Placed";
                newOrder.GoodsID     = goodsID;

                // Calculate desired delivery date
                newOrder.DesiredDeliveryDate = calcDesiredDeliveryDate(deliveryBand, newOrder.Placed);

                // Price of order
                PackageModel packageModel = new PackageModel();
                Package      thisPackage  = packageModel.SearchPackage(packID);
                int          totalPrice   = calcPrice(accountType, deliveryBand, thisPackage);

                // Creates the order
                int orderID = orderModel.CreateOrder(newOrder);

                // Sets up a transaction
                tranHandler.create(orderID, thisAccount.CustomerID, thisAccount.BankID);

                // Passes back to the view
                return(Redirect("/Transaction/transactions"));
            }
            else
            {
                // If not logged in
                return(Redirect("/login.html"));
            }
        }
示例#11
0
        // Creates a new client user
        public ActionResult CreateClient()
        {
            // Ensures logged in
            if (Session["loggedInState"] == null)
            {
                return(Redirect("/403.html"));
            }

            // Checks if logged in
            bool state = (bool)Session["loggedInState"];

            if (state == true)
            {
                // Establishes models
                ClientUserModel cModel = new ClientUserModel();

                // Establishes handlers
                AccountHandler  accHand = new AccountHandler();
                AddressHandler  addHand = new AddressHandler();
                BankHandler     banHand = new BankHandler();
                ContactHandler  conHand = new ContactHandler();
                CustomerHandler cusHand = new CustomerHandler();

                // Extract for account details
                int accountType = int.Parse(Request.Form["accountTypes"]);

                // Extract for bank details
                String sortCode      = Request.Form["sortCode"];
                int    accountNumber = int.Parse(Request.Form["accountNumber"]);

                // Extract for client details
                String username = Request.Form["username"];
                String password = Request.Form["password1"];
                String name     = Request.Form["clientName"];

                // Extract contact details
                String forename    = Request.Form["contactForename"];
                String surname     = Request.Form["contactSurname"];
                String position    = Request.Form["contactPosition"];
                String phoneNumber = Request.Form["contactPhone"];

                // Extract bank address details
                //String blineOne = Request.Form["bankL1"];
                //String blineTwo = Request.Form["bankL2"]; ;
                //String blineThree = Request.Form["bankL3"];
                //String blineFour = Request.Form["bankL4"];
                //String blineFive = Request.Form["bankL5"];
                //String bcState = Request.Form["bankState"];
                //String bcounty = Request.Form["bankCounty"];
                //String bcountry = Request.Form["bankCountry"];
                //String bpostalCode = Request.Form["bankPostalCode"];

                // Extract for customer details
                String compName = Request.Form["clientName"];

                // Extract customer address details
                String clineOne    = Request.Form["address1"];
                String clineTwo    = Request.Form["address2"];;
                String clineThree  = Request.Form["address3"];
                String clineFour   = Request.Form["address4"];
                String clineFive   = Request.Form["address5"];
                String ccState     = Request.Form["state"];
                String ccounty     = Request.Form["county"];
                String ccountry    = Request.Form["country"];
                String cpostalCode = Request.Form["postcode"];

                // Creates objects for user
                //int bankAddressID = addHand.create(blineOne, blineTwo, blineThree, blineFour, blineFive, bcState,
                //                                   bcounty, bcountry, bpostalCode);
                int custAddressID = addHand.create(clineOne, clineTwo, clineThree, clineFour, clineFive, ccState,
                                                   ccounty, ccountry, cpostalCode);
                int bankID     = banHand.create(sortCode, accountNumber);
                int contactID  = conHand.create(forename, surname, position, phoneNumber);
                int customerID = cusHand.create(compName, custAddressID);
                int accountID  = accHand.create(accountType, bankID, customerID, contactID);

                // Holds new objects
                ClientUser newClient = new ClientUser();

                // Acquires needed Account ID
                newClient.Username = username;


                // Stored details for the customer
                newClient.Name      = name;
                newClient.Username  = username;
                newClient.Password  = password;
                newClient.AccountID = accountID;

                // Creates the customer
                int clientID = cModel.CreateClientUser(newClient);

                // Return created department to view
                return(Redirect("/Index/adminIndex"));
            }
            else
            {
                // If not logged in
                return(Redirect("/login.html"));
            }
        }
示例#12
0
        //public ViewResult Add()
        //{
        //    ClientUserModel model = new ClientUserModel();
        //    return View();
        //}

        //public ViewResult Update(int id)
        //{
        //    ClientUserModel model = GetClientUserModel(id);
        //    return View(model);
        //}

        public ViewResult Details(int id)
        {
            ClientUserModel model = GetClientUserModel(id);

            return(View(model));
        }
示例#13
0
        public ActionResult loginpost()
        {
            LoginModel      loginModel   = new LoginModel();
            ClientUserModel clientmModel = new ClientUserModel();

            // To store login details
            String username;
            String password;

            // Acquire login details from front-end
            username = Request.Form[0];
            password = Request.Form[1];

            // Composes object
            User thisUser = new User();

            thisUser.username = username;
            thisUser.password = password;
            ClientUser client = new ClientUser();

            client.Username = username;
            client.Password = password;


            // get Account Type / Access levels from Database
            LoggedIn logState;

            logState = loginModel.Login(thisUser);

            if (logState.State)
            {
                Session["loggedInState"] = logState.State;
                Session["username"]      = thisUser.username;
                Session["userID"]        = logState.UserID;
                Session["Type"]          = "Employee";
            }
            else
            {
                logState = clientmModel.Login(client);

                Session["loggedInState"] = logState.State;
                Session["username"]      = client.Username;
                Session["userID"]        = logState.UserID;
                Session["Type"]          = "Client";
            }

            // Sets the Session variables


            // Acquire type of user from Ryan
            // Redirect based on user:
            // Admin (Staff)
            // User (Client)

            // variable to store the path to redirect to
            String pageToDirectTo = "/index.html";

            try {
                bool state = (bool)Session["loggedInState"];
                if (state == true)
                {
                    if (Session["Type"].ToString() == "Employee")
                    {
                        pageToDirectTo = "/Index/";
                        if (logState.AccessLevel.Equals("Admin"))
                        {
                            pageToDirectTo = "/Index/adminIndex";
                        }
                    }
                    else
                    {
                        pageToDirectTo = "/Index/clientIndex"; // doesn't work
                    }
                }
                else
                {
                    pageToDirectTo = "/login.html";
                }
            }catch (Exception e) {
                pageToDirectTo = "/403.html";
            }

            // redirect the user to the relevant page
            return(Redirect(pageToDirectTo));
        }