Example #1
0
        /// <summary>
        /// Use system user token to perform work
        /// </summary>
        /// <param name="token">Token returned from SuperId and validated</param>
        /// <returns>Contact entity created as the system user</returns>
        private static ContactEntity DoWorkAsSystemUser(SuperIdToken token)
        {
            // Enter database context for the customer (enter the right multi-tenant context)
            using (var context = SoDatabaseContext.EnterDatabaseContext(token.ContextIdentifier))
            {
                // set appropriate url for the customer tenant
                // ConfigFile.WebServices.RemoteBaseURL = token.NetserverUrl;

                // Log in as the system user
                using (var session = SoSession.Authenticate(new SoCredentials(token.Ticket)))
                {
                    // Do work as the system user
                    var principal = SoContext.CurrentPrincipal;
                    System.Diagnostics.Trace.WriteLine(principal.Associate);
                    using (var agent = new ContactAgent())
                    {
                        var timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                        var entity = agent.CreateDefaultContactEntity();
                        entity.Name = "SuperId-" + timestamp;
                        return(agent.SaveContactEntity(entity));
                    }
                }
            }
        }
Example #2
0
        private void btnLogIn_Click(object sender, EventArgs e)
        {
            if (txUsername.Text == "" || txtPassword.Text == "")
            {
                //MetroMessageBox.Show(this, "Your message here.", "Title Here", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
                MetroMessageBox.Show(this, "Please provide Username and Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                Importer.Username = txUsername.Text;
                Importer.Password = txtPassword.Text;
                //Sosession
                try
                {
                    using (var _session = SoSession.Authenticate(txUsername.Text, txtPassword.Text))
                    {
                        string sessionString = string.Empty;

                        EventHandler handler = LogInSuccess;
                        if (handler != null)
                        {
                            handler(this, e);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MetroMessageBox.Show(this, ex.Message + " try again", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
        }
Example #3
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text == "" || txtPassword.Text == "")
            {
                MessageBox.Show("Please provide Username and Password");
                return;
            }
            else
            {
                Username = txtUsername.Text;
                Password = txtPassword.Text;
                //Sosession
                try
                {
                    using (var _session = SoSession.Authenticate(Username, Password))
                    {
                        string sessionString = string.Empty;

                        //sessionString = _session.Suspend();
                        //MessageBox.Show("Logged In");
                        this.Hide();
                        MainWindow main = new MainWindow(Username, Password);
                        //main.WindowState = FormWindowState.Maximized;
                        main.Show();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + " try again");
                }
            }
        }
Example #4
0
        public IEnumerable <AppointmentInfo> GetAppointmentEntitiesFromId(int appointmentId, string ticket,
                                                                          string contextIdentifier, string netserverUrl, Dictionary <string, WishlistElement> infoWishList)
        {
            using (SoDatabaseContext.EnterDatabaseContext(contextIdentifier))
            {
                ConfigFile.WebServices.RemoteBaseURL = netserverUrl;
                using (SoSession.Authenticate(new SoCredentials(ticket)))
                    using (var appAgent = new AppointmentAgent())
                        //using (new AssociateAgent())
                        using (var personAgent = new PersonAgent())
                        {
                            var               appEnts = new List <AppointmentInfo>();
                            AppointmentInfo   appInfo;
                            AppointmentEntity appEntity;
                            do
                            {
                                appEntity = appAgent.GetAppointmentEntity(appointmentId);
                                if (appEntity?.Associate == null)
                                {
                                    continue;
                                }

                                var associatePerson   = personAgent.GetPersonEntity(appEntity.Associate.PersonId);
                                var appointmentPerson = personAgent.GetPersonEntity(appEntity.Person.PersonId);

                                appInfo = new AppointmentInfo
                                {
                                    AppointmentId      = appEntity.AppointmentId,
                                    EmailReceiver      = appointmentPerson.Emails.FirstOrDefault()?.Value,
                                    MessageDescription = appEntity.Description,
                                    Receptionist       = associatePerson.FullName,
                                    RecepTitle         = associatePerson.Title,
                                    SmsPhoneNumber     = appointmentPerson.MobilePhones.FirstOrDefault()?.Value,
                                    CustWantsCallBack  = ResolveVariableInfo(appEntity,
                                                                             infoWishList.FirstOrDefault(k => k.Key == "CustWantsCallBack").Value),
                                    SendSms = ResolveVariableInfo(appointmentPerson,
                                                                  infoWishList.FirstOrDefault(k => k.Key == "SendSms").Value),
                                    CustCallsBack = ResolveVariableInfo(appEntity,
                                                                        infoWishList.FirstOrDefault(k => k.Key == "CustCallsBack").Value),
                                    CustomerHighPriority = ResolveVariableInfo(appEntity,
                                                                               infoWishList.FirstOrDefault(k => k.Key == "CustomerHighPriority").Value),
                                    Customer = ResolveVariableInfo(appEntity,
                                                                   infoWishList.FirstOrDefault(k => k.Key == "Customer").Value),
                                    CustomerContact = ResolveVariableInfo(appEntity,
                                                                          infoWishList.FirstOrDefault(k => k.Key == "CustomerContact").Value),
                                    CustomerContactPhone = ResolveVariableInfo(appEntity,
                                                                               infoWishList.FirstOrDefault(k => k.Key == "CustomerContactPhone").Value),
                                };

                                appEnts.Add(appInfo);
                                appointmentId++;
                                Debug.WriteLine($"AppEntity desc {appInfo.MessageDescription} with ID {appointmentId}");
                            } while (appEntity != null);

                            return(appEnts);
                        }
            }
        }
Example #5
0
        private void btLogin_Click(object sender, EventArgs e)
        {
            btDoStuff.Enabled = false;

            _netServerUrl.Text = string.Empty;
            _claims.Items.Clear();

            SuperOffice.Configuration.ConfigFile.Services.ApplicationToken = _applicationToken.Text;

            var login    = new LoginHelper();
            var uri      = new UriBuilder(_environmentLogin.Text).Uri;
            var response = login.TryFederatedLogin(uri, new AuthenticationRequest()
            {
                ApplicationId    = _applicationId.Text,
                ApplicationTitle = "Testing win-forms login in demo app",
                CustomerContext  = string.Empty,     // don't cara about which customer in this context
            });

            if (response.IsSuccessful)
            {
                var saml = GetClaim(response, "saml");
                //var jwt = GetClaim(response, "jwt");

                // Validate and parse saml with user authentication
                var userTokenHandler = new SuperIdTokenHandler();
                _userToken = userTokenHandler.ValidateToken(saml, SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Saml);


                foreach (var claim in _userToken.Claims)
                {
                    var lvi = new ListViewItem(claim.ClaimType);
                    lvi.SubItems.Add(claim.Resource as string);
                    _claims.Items.Add(lvi);
                }

                _netServerUrl.Text = _userToken.NetserverUrl;
                ConfigFile.WebServices.RemoteBaseURL = _userToken.NetserverUrl;

                try
                {
                    _session = SoSession.Authenticate(new SoCredentials()
                    {
                        Ticket = _userToken.Ticket
                    });
                }
                catch (Exception)
                {
                }
            }

            btDoStuff.Enabled = _session != null;
        }
Example #6
0
        protected override TResponse Execute <TRequest, TResponse>(TRequest request, Action <IQuoteConnector, TResponse> action)
        {
            using (SoDatabaseContext.EnterDatabaseContext(request.ContextIdentifier))
            {
                var systemUserToken = SystemUserManager.GetSystemUserToken(request.ContextIdentifier);
                SuperOffice.Configuration.ConfigFile.WebServices.RemoteBaseURL = systemUserToken.NetserverUrl;

                using (SoSession session = SoSession.Authenticate(new SoCredentials()
                {
                    Ticket = systemUserToken.Ticket
                }))
                {
                    return(base.Execute <TRequest, TResponse>(request, action));
                }
            }
        }
        private static void SyncCustomers()
        {
            var customerDataSource = new SuperOffice.DevNet.Online.SystemUser.PartnerDBLibrary.Models.CustomerDataSource();

            foreach (var customer in customerDataSource.Customers)
            {
                Log("Getting System User Token.");

                var token = GetSystemUserToken(customer.SystemUserToken, customer.ContextIdentifier);

                if (token != null)
                {
                    // Enter database context for the customer (enter the right multi-tenant context)
                    using (var context = SoDatabaseContext.EnterDatabaseContext(token.ContextIdentifier))
                    {
                        // set appriiriate url for the customer tenant
                        ConfigFile.WebServices.RemoteBaseURL = token.NetserverUrl;

                        try
                        {
                            // Log in as the system user
                            using (var session = SoSession.Authenticate(new SoCredentials(token.Ticket)))
                            {
                                //var listHelper = new SuperOffice.DevNet.Online.Provisioning.ListHelper();
                                //listHelper.CreateSaleSourceListItem("NewSaleSource", "NewSaleSourceToolTip");

                                //// Do work as the system user
                                Log("Logged on to context {0} as {1}", token.ContextIdentifier, SoContext.CurrentPrincipal == null ? "Unknown" : SoContext.CurrentPrincipal.Associate);
                            }
                        }
                        catch (Exception ex)
                        {
                            while (ex.InnerException != null)
                            {
                                ex = ex.InnerException;
                            }

                            Log("Exception during authentication for customer {0}: {1}", token.ContextIdentifier, ex.Message);
                        }
                    }
                }
                else
                {
                    Log("Unable to get token for customer {0}.", customer.ContextIdentifier);
                }
            }
        }
Example #8
0
 private void btnProcess_Click(object sender, EventArgs e)
 {
     using (SoSession.Authenticate(Username, Password))
     {
         progressBar.Value   = 0;
         progressBar.Maximum = selectedBox;
         progressBar.Step    = 1;
         bool noneSelected = true;
         foreach (DataGridViewRow item in dtUsersList.Rows)
         {
             if (Convert.ToBoolean(item.Cells["selectColumn"].Value) == true)
             {
                 string associateId = item.Cells["AssociateId"].Value.ToString();
                 string firstname   = item.Cells["FirstName"].Value.ToString();
                 string lastname    = item.Cells["LastName"].Value.ToString();
                 string fullname    = item.Cells["FullName"].Value.ToString();
                 string username    = item.Cells["UserName"].Value.ToString();
                 string email       = item.Cells["Email"].Value.ToString();
                 string role        = item.Cells["Role"].Value.ToString();
                 string group       = item.Cells["UserGroup"].Value.ToString();
                 string company     = item.Cells["Company"].Value.ToString();
                 bool   processed   = false;
                 if (associateId != "")
                 {
                     processed = updateUser(associateId, firstname, lastname, fullname, username, email, role, group, DefaultLicense, item);
                 }
                 else
                 {
                     processed = createUser(firstname, lastname, fullname, username, email, role, group, company, DefaultLicense, item);
                 }
                 if (processed)
                 {
                     progressBar.PerformStep();
                     item.Cells["Status"].Value = "Processed";
                 }
                 noneSelected = false;
             }
         }
         if (noneSelected)
         {
             MessageBox.Show("No entries selected");
         }
     }
 }
Example #9
0
    protected void LoginBtn_Click(object sender, EventArgs e)
    {
        //Retriving the user name and password and assigning them to Session variables
        //UserName
        TextBox un = soLogin.FindControl("UserName") as TextBox;

        Session["UserName"] = un.Text;

        //Password
        TextBox pw = soLogin.FindControl("Password") as TextBox;

        Session["passWord"] = pw.Text;

        using (SoSession mySession = SoSession.Authenticate(Session["UserName"].ToString(), Session["passWord"].ToString()))
        {
            //Transfering to the Appointments page
            Server.Transfer("Appointments.aspx");
        }
    }
        private TreeNode[] AuthenticateAndPopulate(string user, string pwd)
        {
            TreeNode[] r = null;
            try
            {
                if (session == null || !session.IsOpen)
                    session = SoSession.Authenticate(user, pwd);

                r = PopulateData();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    while (ex.InnerException != null)
                        ex = ex.InnerException;

                MessageBox.Show("Error Authenticating", ex.Message, MessageBoxButtons.OK);
            }
            return r;
        }
Example #11
0
 static void Main(string[] args)
 {
     try
     {
         Settings.DefaultExecutionContext     = (action) => action.DateTimeToUTC = true;
         ConfigFile.Services.ApplicationToken = ConfigurationManager.AppSettings["SoAppToken"];
         ConfigFile.Services.RemoteBaseURL    = ConfigurationManager.AppSettings["SoBaseUrl"];
         using (SoSession.Authenticate(ConfigurationManager.AppSettings["SoUser"], ConfigurationManager.AppSettings["SoPass"]))
         {
             var r = new Queryable <Person>().Where(x => x.ContactId == 2).ToList();
         }
     }
     catch (Exception ex)
     {
         if (ex.InnerException?.InnerException is SoServerException)
         {
             var serverEx = (SoServerException)ex.InnerException?.InnerException;
             throw new Exception(serverEx.ExceptionInfo?.Message ?? serverEx.Message, serverEx);
         }
         throw;
     }
 }
Example #12
0
    protected void datesBtn_Click(object sender, EventArgs e)
    {
        using (SoSession mySession = SoSession.Authenticate(Session["UserName"].ToString().Trim(), Session["passWord"].ToString().Trim()))
        {
            //retrieve user inputs and store them in variables
            TextBox ai = form1.FindControl("assoicateID") as TextBox;
            TextBox ad = form1.FindControl("activeDate") as TextBox;
            TextBox ed = form1.FindControl("endDate") as TextBox;

            //converting the values to the format required by the method
            int      personID   = int.Parse(ai.Text);
            DateTime activeDate = DateTime.Parse(ad.Text);
            DateTime endDate    = DateTime.Parse(ed.Text);

            //retrive the appointments list using the Agent
            AppointmentAgent newAppAgt = new AppointmentAgent();

            ActivityInformationListItem[] newAppArr = newAppAgt.GetActivityInformationListByDatesAndAssociate(activeDate, endDate, 103);

            //Displaying the Appointments between a given date range of and Associate
            for (int i = 0; i < newAppArr.Length; i++)
            {
                //Instantiate table rows and table cells
                HtmlTableCell tblcelldate = new HtmlTableCell();
                HtmlTableCell tblcellday  = new HtmlTableCell();
                HtmlTableRow  tblrow      = new HtmlTableRow();

                //Assigning data to the table
                tblcelldate.Controls.Add(new LiteralControl(newAppArr[i].Date.Date.ToString("dd/MM/yyyy")));
                tblcellday.Controls.Add(new LiteralControl(newAppArr[i].Date.DayOfWeek.ToString()));
                tblrow.Controls.Add(tblcelldate);
                tblrow.Controls.Add(tblcellday);
                tblid.Controls.Add(tblrow);
                datesBtn.Visible = false;
            }
        }
    }
Example #13
0
        private void btnLoadFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (var _session = SoSession.Authenticate(Username, Password))
                {
                    DataGridViewComboBoxColumn rolesColumn = (DataGridViewComboBoxColumn)dtUsersList.Columns["Role"];
                    rolesColumn.DataSource    = roles.ToList();
                    rolesColumn.DisplayMember = "Name";

                    DataGridViewComboBoxColumn groupsColumn = (DataGridViewComboBoxColumn)dtUsersList.Columns["UserGroup"];
                    groupsColumn.DataSource    = groups.ToList();
                    groupsColumn.DisplayMember = "Value";
                    p = new FileParser(openFileDialog.FileName);

                    MessageBox.Show("File parsed, " + p.UserInfos.Count.ToString() + " users read\n");

                    foreach (ImportUserInfo ui in p.UserInfos)
                    {
                        ContactTableInfo          cti  = TablesInfo.GetContactTableInfo();
                        OwnerContactLinkTableInfo octi = TablesInfo.GetOwnerContactLinkTableInfo();
                        Select findOc = S.NewSelect("Find OC");

                        findOc.JoinRestriction.InnerJoin(cti.ContactId.Equal(octi.ContactId));

                        // if contact name contains a comma, assume that pre-comma is name and post-comma is department (db & file are set up that way)
                        if (ui.Company.Contains(","))
                        {
                            findOc.Restriction = cti.Name.Equal(S.Parameter(ui.Company.Split(',')[0].Trim())).
                                                 And(cti.Department.Equal(S.Parameter(ui.Company.Split(',')[1].Trim())));
                        }
                        else
                        {
                            findOc.Restriction = cti.Name.Equal(S.Parameter(ui.Company));
                        }

                        findOc.ReturnFields.Add(cti.ContactId);

                        int ocId = QueryExecutionHelper.ExecuteTypedScalar <int>(findOc);

                        if (ocId == 0)
                        {
                            //MessageBox.Show("Owner company " + ui.Company + "(referenced by " + ui.UID + ")  does not exist OR is not an Owner Company - setting to License Owner " + SoSystemInfo.GetCurrent().CompanyName);
                            ui.Company = SoSystemInfo.GetCurrent().CompanyName;
                            if (!_contacts.ContainsKey(SoSystemInfo.GetCurrent().CompanyName))
                            {
                                _contacts.Add(ui.Company, SoSystemInfo.GetCurrent().CompanyId);
                            }
                        }
                        else if (!_contacts.ContainsKey(ui.Company))
                        {
                            _contacts.Add(ui.Company, ocId);
                        }

                        if (!_roles.ContainsKey(ui.Role))
                        {
                            ui.Role = DefaultRole;
                        }
                        if (!_groups.ContainsKey(ui.Group))
                        {
                            ui.Group = DefaultGroup;
                        }
                    }
                    Dictionary <string, int> users = Importer.FindUsers();

                    dtUsersList.AutoGenerateColumns = false;
                    dtUsersList.Columns["FirstName"].DataPropertyName   = "FirstName";
                    dtUsersList.Columns["LastName"].DataPropertyName    = "LastName";
                    dtUsersList.Columns["FullName"].DataPropertyName    = "FullName";
                    dtUsersList.Columns["UserName"].DataPropertyName    = "UID";
                    dtUsersList.Columns["Email"].DataPropertyName       = "Email";
                    dtUsersList.Columns["Role"].DataPropertyName        = "Role";
                    dtUsersList.Columns["UserGroup"].DataPropertyName   = "Group";
                    dtUsersList.Columns["Company"].DataPropertyName     = "Company";
                    dtUsersList.Columns["AssociateId"].DataPropertyName = "AssociateId";
                    dtUsers = Importer.ConvertToDataTable <ImportUserInfo>(p.UserInfos);
                    dtUsersList.DataSource = dtUsers;
                    //dtUsersList.DataSource = p.UserInfos;
                    progressBar.Value = 0;
                    foreach (DataGridViewRow item in dtUsersList.Rows)
                    {
                        string username = item.Cells["UserName"].Value.ToString();
                        if (users.ContainsKey(username))
                        {
                            item.Cells["Status"].Value      = "Exists";
                            item.Cells["AssociateId"].Value = users[username];
                            string license = Importer.GetLicense(users[username], LookupList);
                            item.Cells["AssignedLicenses"].Value = license;
                        }
                        else
                        {
                            item.Cells["AssociateId"].Value      = DBNull.Value;
                            item.Cells["Status"].Value           = "New";
                            item.Cells["AssignedLicenses"].Value = "";
                        }
                    }
                }
                btnProcess.Enabled = true;
                progressBar.Value  = 0;
                txtSearch.Text     = "";
                lblSearch.Visible  = true;
                txtSearch.Visible  = true;
            }
        }
        private TreeNode[] PopulateData()
        {
            List<string> r = new List<string>();

            // Session is Open
            if (session.IsOpen && session.Principal != null)
            {
                // Database info
                SoDatabase db = SoDatabase.GetCurrent();

                r.Add("Netserver in use:");
                r.Add("Name: " + SuperOffice.NetServerVersion.FullName);
                r.Add("Build: " + SuperOffice.NetServerVersion.Build.ToString());
                r.Add("Version: " + SuperOffice.NetServerVersion.Version.ToString());

                r.Add("*******************************");
                r.Add("Database information:");
                r.Add("Company Name: " + db.CompanyName);
                r.Add("Database Name: " + db.Database);
                r.Add("Serial Number: " + db.SerialNumber);

                // User info
                Contact c = Contact.GetFromIdxContactId(session.Principal.ContactId);

                r.Add("*******************************");
                r.Add("Associate information:");
                r.Add("Name: " + session.Principal.Associate);
                r.Add("Id: " + session.Principal.AssociateId.ToString());
                r.Add("Full Name: " + session.Principal.FullName);

                r.Add("*******************************");
                r.Add("Associate Company Information:");
                r.Add("Name: " + c.Name);
                r.Add("Country: " + c.Country.EnglishName);
                r.Add("OrgNr: " + c.OrgNr);
                r.Add("Total Persons: " + c.Persons.Count());
                r.Add("*******************************");

                session.Close();
                session = null;
            }

            // convert and return
            List<TreeNode> tnodes = new List<TreeNode>();
            foreach (var str in r)
                tnodes.Add(new TreeNode(str));

            return tnodes.ToArray();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="token">Saml or JWT token</param>
        public static bool TryLogin(string token, string tokenType)
        {
            var tokenHandler = new SuperIdTokenHandler();


            var typedTokenType = (SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType)
                                 Enum.Parse(typeof(SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType), tokenType);

            var certificatePath = ConfigManager.SuperOfficeFederatedLogin;

            if (!String.IsNullOrWhiteSpace(certificatePath))
            {
                if (!Path.IsPathRooted(certificatePath))
                {
                    certificatePath = Path.Combine(HostingEnvironment.MapPath(@"~"), certificatePath);
                }

                tokenHandler.JwtIssuerSigningCertificate =
                    new System.Security.Cryptography.X509Certificates.X509Certificate2(certificatePath);
            }
            else
            {
                tokenHandler.CertificateValidator = X509CertificateValidator.PeerTrust;
            }

            //tokenHandler.ValidateAudience = false;
            var superIdClaims = tokenHandler.ValidateToken(token, typedTokenType);

            var context = new SuperOfficeContext
            {
                Ticket            = superIdClaims.Ticket,
                Email             = superIdClaims.Email,
                ContextIdentifier = superIdClaims.ContextIdentifier,
                NetServerUrl      = superIdClaims.NetserverUrl,
                SystemToken       = superIdClaims.SystemToken,
            };

            Context = context;

            // Use forms authentication - this is optional
            var soFormsTicket          = new FormsAuthenticationTicket(superIdClaims.Email, false, 3600);
            var soFormsTicketEncrypted = FormsAuthentication.Encrypt(soFormsTicket);

            var httpContext = HttpContext.Current;

            httpContext.Session[ConfigManager.SoAuthCookie] = soFormsTicketEncrypted;
            httpContext.Response.Cookies.Add(new HttpCookie(ConfigManager.SoAuthCookie, soFormsTicketEncrypted));


            try
            {
                // If request is not authenticated, and a controller with the
                // SuperOfficeAuthorize attribute is accessed, the called controller
                // will continue to send the user to SuperID. If already authenticated there
                // this user will always return here and be stuck in an endless loop.
                // Therefore, it is important to authenticate with NetServer, and allow the
                // context provider to store the current session. Thus, the SuperOfficeAuthorize
                // attibute will be able to locate the session and proceed unimpeded

                //Authenticate with NetServer using web services if necessary.
                SoSession session = SoSession.Authenticate(new SoCredentials()
                {
                    Ticket = context.Ticket
                });

                var principal = SoContext.CurrentPrincipal;
                var contact   = new ContactAgent().GetContact(principal.ContactId);

                context.Company     = contact.FullName;
                context.Name        = principal.FullName;
                context.Username    = principal.Associate;
                context.AssociateId = principal.AssociateId;

                return(true);
            }
            catch (Exception ex)
            {
                SuperOfficeAuthHelper.Logout();
                return(false);
            }
        }
        /// <summary>
        /// Does the actual authentication
        /// </summary>
        /// <param name="context"></param>
        /// <param name="errorReason"></param>
        /// <returns></returns>
        public static bool TryLogin(SuperOfficeContext context, out string errorReason)
        {
            Context = context;

            //If we are allready authorized, then logout first, before creating a cookie....
            if (SuperOffice.SoContext.IsAuthenticated)
            {
                SuperOffice.SoContext.CloseCurrentSession();
                SuperOfficeAuthHelper.Logout();
            }

            // Use forms authentication - this is optional
            var soFormsTicket          = new FormsAuthenticationTicket(context.Email, false, 3600);
            var soFormsTicketEncrypted = FormsAuthentication.Encrypt(soFormsTicket);

            var httpContext = HttpContext.Current;

            httpContext.Session[ConfigManager.SoAuthCookie] = soFormsTicketEncrypted;
            httpContext.Response.Cookies.Add(new HttpCookie(ConfigManager.SoAuthCookie, soFormsTicketEncrypted));



            try
            {
                // If request is not authenticated, and a controller with the
                // SuperOfficeAuthorize attribute is accessed, the called controller
                // will continue to send the user to SuperID. If already authenticated there
                // this user will always return here and be stuck in an endless loop.
                // Therefore, it is important to authenticate with NetServer, and allow the
                // context provider to store the current session. Thus, the SuperOfficeAuthorize
                // attibute will be able to locate the session and proceed unimpeded

                //Authenticate with NetServer using web services if necessary.

                /*
                 * //    From Jens on DevNet:
                 * //    The SuperOffice.Configuration.ConfigFile.WebServices.RemoteBaseUrl is the value actually being used by the proxy to communicate with the server.
                 * //    This value is read from SuperOffice.Configuration.ConfigFile.Services.RemoteBaseUrl if it is not defined.
                 * //    The values of SuperOffice.Configuration.ConfigFile.Services are stored in a value that is static throughout the NetServer process,
                 * //    and shared between tenants in a multi-tenant configuration.
                 * //    The values SuperOffice.Configuration.ConfigFile.WebServices are tenant specific configuration values.
                 * //    */
                //}

                SoSession session = null;

                if (string.IsNullOrEmpty(context.AccessToken))
                {
                    session = SoSession.Authenticate(new SoCredentials()
                    {
                        Ticket = context.Ticket
                    });
                }
                else
                {
                    session = SoSession.Authenticate(new SoAccessTokenSecurityToken(context.AccessToken));
                }

                var principal = SoContext.CurrentPrincipal;
                OverrideContextIdentifier(principal, context.ContextIdentifier);
                var contact = new ContactAgent().GetContact(principal.ContactId);

                context.Company     = contact.FullName;
                context.Name        = principal.FullName;
                context.Username    = principal.Associate;
                context.AssociateId = principal.AssociateId;

                errorReason = String.Empty;

                return(true);
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                errorReason = ex.Message;
                SuperOfficeAuthHelper.Logout();
                return(false);
            }
        }
Example #17
0
        public SettingsForm(Form owner)
            : base(owner)
        {
            InitializeComponent();

            for (int i = 3; i < 13; i++)
            {
                MetroTile _tile = new MetroTile();
                _tile.Size  = new Size(30, 30);
                _tile.Tag   = i;
                _tile.Style = (MetroColorStyle)i;
                //_tile.Click += _tile_Click;
            }

            using (var session = SoSession.Authenticate(Importer.Username, Importer.Password))
            {
                UserAgent _agent = new UserAgent();
                roles = _agent.GetAllRoles(SuperOffice.Data.RoleType.Employee);
                for (int i = 0; i < roles.Length; i++)
                {
                    _roles.Add(roles[i].Name, roles[i].Id);
                }

                groups = _agent.GetAllUserGroups(false);
                for (int j = 0; j < groups.Length; j++)
                {
                    _groups.Add(groups[j].Value, groups[j].Id);
                }

                cmbRole.DataSource     = roles.ToList();
                cmbRole.DisplayMember  = "Name";
                cmbGroup.DataSource    = groups.ToList();
                cmbGroup.DisplayMember = "Value";

                Importer.Groups = _groups;
                Importer.Roles  = _roles;

                LicenseAgent            agent           = new LicenseAgent();
                ExtendedLicenseInfo     extendedLicense = agent.GetLicenseFromDB("SuperOffice");
                ExtendedModuleLicense[] moduleLicense   = extendedLicense.ExtendedModuleLicenses;
                ExtendedModuleLicense   sales_users;
                ExtendedModuleLicense   service_users;
                ExtendedModuleLicense   complete_users;
                sales_users    = moduleLicense.FirstOrDefault(c => c.Current.ModuleName.Equals(SoLicenseNames.SuperLicenseSalesPro.Substring(SoLicenseNames.SuperLicenseSalesPro.LastIndexOf('.') + 1)));
                service_users  = moduleLicense.FirstOrDefault(c => c.Current.ModuleName.Equals(SoLicenseNames.SuperLicenseServicePro.Substring(SoLicenseNames.SuperLicenseServicePro.LastIndexOf('.') + 1)));
                complete_users = moduleLicense.FirstOrDefault(c => c.Current.ModuleName.Equals(SoLicenseNames.SuperLicenseComplete.Substring(SoLicenseNames.SuperLicenseComplete.LastIndexOf('.') + 1)));
                Dictionary <string, string> lic = new Dictionary <string, string>();
                List <string> LookupList        = new List <string>();

                if (sales_users != null)
                {
                    lic.Add(sales_users.Current.ModuleDescription + " (" + sales_users.NumberOfLicensesTotal + ")", sales_users.Current.ModuleName);
                    LookupList.Add(sales_users.Current.ModuleName);
                }
                if (service_users != null)
                {
                    lic.Add(service_users.Current.ModuleDescription + " (" + service_users.NumberOfLicensesTotal + ")", service_users.Current.ModuleName);
                    LookupList.Add(service_users.Current.ModuleName);
                }
                if (complete_users != null)
                {
                    lic.Add(complete_users.Current.ModuleDescription + " (" + complete_users.NumberOfLicensesTotal + ")", complete_users.Current.ModuleName);
                    LookupList.Add(complete_users.Current.ModuleName);
                }
                cmbLicense.DisplayMember = "Key";
                cmbLicense.DataSource    = lic.ToList();
                Importer.LookupList      = LookupList;
            }

            if (Importer.DefaultConfig == true)
            {
                cmbLicense.SelectedIndex = cmbLicense.FindString(Importer.DefaultLicense);
                cmbGroup.SelectedIndex   = cmbGroup.FindString(Importer.DefaultGroup);
                cmbRole.SelectedIndex    = cmbRole.FindString(Importer.DefaultRole);
            }
        }