Example #1
0
        public ActionResult AddPermission(string groupid, string email, int accessType)
        {
            if (email == null)
            {
                return(Ok(new { Data = "User not found..." }));
            }

            string userid = "QuantAppSecure_" + email.ToLower().Replace('@', '.').Replace(':', '.');

            QuantApp.Kernel.User user = QuantApp.Kernel.User.FindUser(userid);

            if (user != null)
            {
                QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup(groupid);
                if (group == null)
                {
                    group = QuantApp.Kernel.Group.FindGroup(groupid.Replace("_WorkSpace", ""));
                }

                if (group == null)
                {
                    group = QuantApp.Kernel.Group.CreateGroup(groupid, groupid);
                }


                group.Add(user, typeof(QuantApp.Kernel.User), (AccessType)accessType);

                return(Ok(new { Data = "ok" }));
            }

            return(Ok(new { Data = "User not found..." }));
        }
        public ActionResult SetPermission(string userid, string groupid, int accessType)
        {
            string userId = this.User.QID();

            if (userId == null)
            {
                return(null);
            }

            QuantApp.Kernel.User  user  = QuantApp.Kernel.User.FindUser(userid);
            QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup(groupid);
            if (group == null)
            {
                group = QuantApp.Kernel.Group.FindGroup(groupid.Replace("_Workflow", ""));
            }

            if (group == null)
            {
                group = QuantApp.Kernel.Group.CreateGroup(groupid, groupid);
            }

            group.Add(user, typeof(QuantApp.Kernel.User), (AccessType)accessType);

            return(Ok(new { Data = "ok" }));
        }
        public ActionResult SetPermission(string pid, string groupid, int accessType, int year = 9999, int month = 12, int day = 31)
        {
            string userId = this.User.QID();

            if (userId == null)
            {
                return(null);
            }

            QuantApp.Kernel.IPermissible permissible = QuantApp.Kernel.User.FindUser(pid);

            if (permissible == null)
            {
                permissible = QuantApp.Kernel.User.FindUserBySecret(pid);
            }

            if (permissible == null)
            {
                permissible = FileRepository.File(pid);
            }

            if (permissible == null)
            {
                return(BadRequest(new { Data = "Permissible ID was not found" }));
            }

            try
            {
                var testAccesss = (AccessType)accessType;
            }
            catch
            {
                return(BadRequest(new { Data = "accessType needs to be an integer between -2 and 2" }));
            }

            QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup(groupid);
            if (group == null)
            {
                group = QuantApp.Kernel.Group.FindGroup(groupid.Replace("_Workflow", ""));
            }

            if (group == null)
            {
                group = QuantApp.Kernel.Group.CreateGroup(groupid, groupid);
            }

            group.Add(permissible, typeof(QuantApp.Kernel.User), (AccessType)accessType, new DateTime(year, month, day));

            return(Ok(new { Data = "ok" }));
        }
        public ActionResult AddPermission(string groupid, string email, int accessType, int year = 9999, int month = 12, int day = 31)
        {
            if (email == null)
            {
                return(BadRequest(new { Data = "User not found..." }));
            }

            try
            {
                var testAccesss = (AccessType)accessType;
            }
            catch
            {
                return(BadRequest(new { Data = "accessType needs to be an integer between -2 and 2" }));
            }

            string userid = "QuantAppSecure_" + email.ToLower().Replace('@', '.').Replace(':', '.');

            QuantApp.Kernel.User user = QuantApp.Kernel.User.FindUser(userid);

            if (user != null)
            {
                QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup(groupid);
                if (group == null)
                {
                    group = QuantApp.Kernel.Group.FindGroup(groupid.Replace("_Workflow", ""));
                }

                if (group == null)
                {
                    group = QuantApp.Kernel.Group.CreateGroup(groupid, groupid);
                }


                group.Add(user, typeof(QuantApp.Kernel.User), (AccessType)accessType, new DateTime(year, month, day));

                return(Ok(new { Data = "ok" }));
            }

            return(BadRequest(new { Data = "User not found..." }));
        }
Example #5
0
        public async Task <ActionResult> Register([FromBody] SecureRegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                string id = "QuantAppSecure_" + model.Email.ToLower().Replace('@', '.').Replace(':', '.');
                QuantApp.Kernel.User quser = QuantApp.Kernel.User.FindUser(id);
                if (quser == null)
                {
                    var user = UserRepository.CreateUser(System.Guid.NewGuid().ToString(), "QuantAppSecure");

                    user.FirstName = model.FirstName;
                    user.LastName  = model.LastName;
                    user.Email     = model.Email.ToLower();

                    string profile = model.GroupID;

                    user.TenantName = id;
                    user.Hash       = QuantApp.Kernel.Adapters.SQL.Factories.SQLUserFactory.GetMd5Hash(model.Password);

                    if (model.Secret != null)
                    {
                        if (_secrets.ContainsKey(model.Secret))
                        {
                            user.Secret = _secrets[model.Secret];
                        }
                    }

                    var sessionKey = System.Guid.NewGuid().ToString();
                    sessionKeys.TryAdd(sessionKey, user.Secret);
                    revSessionKeys.TryAdd(user.Secret, sessionKey);
                    Response.Cookies.Append("coflows", sessionKey, new CookieOptions()
                    {
                        Expires = DateTime.Now.AddHours(24)
                    });

                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Email, user.Email)
                    };

                    var key   = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                        issuer: "coflows-ce",
                        audience: "coflows-ce",
                        claims: claims,
                        expires: DateTime.Now.AddDays(10),
                        signingCredentials: creds);



                    quser = QuantApp.Kernel.User.FindUser(id);
                    QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup("Public");
                    group.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);

                    QuantApp.Kernel.Group gp = Group.FindGroup(profile);
                    if (gp != null)
                    {
                        gp.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);
                    }

                    return(Ok(new
                    {
                        User = quser.ToUserData(),
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        Secret = quser.Secret,
                        Session = sessionKey
                    }));
                }
                else
                {
                    return(BadRequest(new { Value = false, ID = "Email is already in use..." }));
                }
            }

            string messages = string.Join("<br\\> ", ModelState.Values
                                          .SelectMany(x => x.Errors)
                                          .Select(x => x.ErrorMessage));

            return(Ok(new { Value = false, ID = messages }));
        }
Example #6
0
        public static List <object> GraphUsers(string access_code)
        {
            if (!(Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null))
            {
                return(null);
            }

            var defGroupId = Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"] != null ? Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"].ToString() : "";


            string res = "";

            Task.Run(async() => {
                using (HttpClient httpClient = new HttpClient()){
                    httpClient.Timeout = Timeout.InfiniteTimeSpan;
                    // string access_code = getToken();

                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_code);

                    var req  = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$select=identities,surname,givenName");
                    var data = await httpClient.SendAsync(req);
                    res      = await data.Content.ReadAsStringAsync();
                }
            }).Wait();

            var users = JObject.Parse(res);

            var result = new List <object>();

            foreach (var user in users["value"])
            {
                var email = "";
                foreach (var identity in user["identities"])
                {
                    if (identity["signInType"].ToString() == "emailAddress")
                    {
                        email = identity["issuerAssignedId"].ToString();
                    }
                }

                var firstName = user["givenName"].ToString();
                var lastName  = user["surname"].ToString();

                result.Add(new { Email = email, FirstName = firstName, LastName = lastName });

                //Sync to CoFlows users.
                if (email != "")
                {
                    var qid   = "QuantAppSecure_" + email.ToLower().Replace('@', '.').Replace(':', '.');
                    var quser = QuantApp.Kernel.User.FindUser(qid);

                    if (quser == null)
                    {
                        Console.WriteLine("--- CREATE NEW USER: "******"QuantAppSecure");

                        nuser.FirstName = firstName != null ? firstName : "No first name";
                        nuser.LastName  = lastName != null ? lastName : "No last name";
                        nuser.Email     = email.ToLower();

                        nuser.TenantName = qid;
                        nuser.Hash       = QuantApp.Kernel.Adapters.SQL.Factories.SQLUserFactory.GetMd5Hash(System.Guid.NewGuid().ToString());

                        nuser.Secret = QuantApp.Engine.Code.GetMd5Hash(qid);

                        quser = QuantApp.Kernel.User.FindUser(qid);
                        QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup("Public");
                        group.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);

                        QuantApp.Kernel.Group gp = Group.FindGroup(defGroupId);
                        if (gp != null)
                        {
                            gp.Add(quser, typeof(QuantApp.Kernel.User), AccessType.View);
                        }
                    }
                }
            }

            return(result);
        }
Example #7
0
        public static List <object> GraphGroups(string access_code)
        {
            if (!(Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null))
            {
                return(null);
            }

            var defGroupId = Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"] != null ? Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"].ToString() : "";
            var defGroup   = QuantApp.Kernel.Group.FindGroup(defGroupId);

            string res    = "";
            var    result = new List <object>();

            Task.Run(async() => {
                using (HttpClient httpClient = new HttpClient()){
                    httpClient.Timeout = Timeout.InfiniteTimeSpan;

                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_code);

                    var req  = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/groups");
                    var data = await httpClient.SendAsync(req);

                    res = await data.Content.ReadAsStringAsync();

                    var groups = JObject.Parse(res);

                    foreach (var group in groups["value"])
                    {
                        var id   = group["id"].ToString();
                        var name = group["displayName"].ToString();

                        req  = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/groups/" + id + "/members?$select=identities,surname,givenName");
                        data = await httpClient.SendAsync(req);

                        res = await data.Content.ReadAsStringAsync();

                        var members = JObject.Parse(res);

                        var sub_result = new List <object>();


                        // Create Group
                        var qgroup = QuantApp.Kernel.Group.FindGroup(id);
                        if (qgroup == null)
                        {
                            qgroup        = QuantApp.Kernel.Group.CreateGroup(name, id);
                            qgroup.Parent = defGroup;
                        }

                        foreach (var member in members["value"])
                        {
                            var email = "";
                            foreach (var identity in member["identities"])
                            {
                                if (identity["signInType"].ToString() == "emailAddress")
                                {
                                    email = identity["issuerAssignedId"].ToString();
                                }
                            }

                            var firstName = member["givenName"].ToString();
                            var lastName  = member["surname"].ToString();

                            sub_result.Add(new { Email = email, FirstName = firstName, LastName = lastName });

                            if (email != "")
                            {
                                var qid   = "QuantAppSecure_" + email.ToLower().Replace('@', '.').Replace(':', '.');
                                var quser = QuantApp.Kernel.User.FindUser(qid);

                                if (quser == null)
                                {
                                    var nuser = UserRepository.CreateUser(System.Guid.NewGuid().ToString(), "QuantAppSecure");

                                    nuser.FirstName = firstName != null ? firstName : "No first name";
                                    nuser.LastName  = lastName != null ? lastName : "No last name";
                                    nuser.Email     = email.ToLower();

                                    nuser.TenantName = qid;
                                    nuser.Hash       = QuantApp.Kernel.Adapters.SQL.Factories.SQLUserFactory.GetMd5Hash(System.Guid.NewGuid().ToString());

                                    nuser.Secret = QuantApp.Engine.Code.GetMd5Hash(qid);

                                    quser = QuantApp.Kernel.User.FindUser(qid);
                                    QuantApp.Kernel.Group publicGroup = QuantApp.Kernel.Group.FindGroup("Public");
                                    publicGroup.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);

                                    if (defGroup != null)
                                    {
                                        defGroup.Add(quser, typeof(QuantApp.Kernel.User), AccessType.View);
                                    }
                                }

                                if (qgroup != null)
                                {
                                    qgroup.Add(quser, typeof(QuantApp.Kernel.User), AccessType.View);
                                }
                            }
                        }

                        List <IPermissible> users = qgroup.Master.List(QuantApp.Kernel.User.CurrentUser, typeof(QuantApp.Kernel.User), false);
                        foreach (var u in users)
                        {
                            var qu     = u as QuantApp.Kernel.User;
                            var emails = sub_result.Where(x => {
                                dynamic d = x;
                                return(d.Email == qu.Email);
                            });

                            var perm = qgroup.Permission(null, qu);

                            if (emails.Count() == 0 && perm != AccessType.Write)
                            {
                                qgroup.Remove(qu);
                            }
                        }

                        result.Add(new { ID = id, Name = name, Members = sub_result });
                    }
                }
            }).Wait();

            return(result);
        }
        public async void GitHub(string groupid, string code)
        {
            if (Program.config["Server"]["OAuth"] == null || Program.config["Server"]["OAuth"]["GitHub"] == null)
            {
                return;
            }

            string access_code = "";

            using (HttpClient httpClient = new HttpClient()){
                httpClient.Timeout = Timeout.InfiniteTimeSpan;

                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var res = httpClient.PostAsync(
                    "https://github.com/login/oauth/access_token",
                    new {
                    client_id     = Program.config["Server"]["OAuth"]["GitHub"]["ClientId"].ToString(),
                    client_secret = Program.config["Server"]["OAuth"]["GitHub"]["ClientSecret"].ToString(),
                    code          = code
                }.AsJson()).Result;

                var data = res.Content.ReadAsStringAsync().Result;

                dynamic d = JObject.Parse(data);
                access_code = d.access_token;
            }

            string email = "";
            string name  = "";


            //Name & Email
            try
            {
                using (HttpClient httpClient = new HttpClient()){
                    httpClient.Timeout = Timeout.InfiniteTimeSpan;

                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", access_code);
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "CoFlows");

                    var res = httpClient.GetAsync("https://api.github.com/user").Result;

                    var data = res.Content.ReadAsStringAsync().Result;

                    dynamic d = JObject.Parse(data);
                    email = d.Email;
                    name  = d.Name;
                }
            }
            catch { }

            if (string.IsNullOrEmpty(email))
            {
                //If Email fails above...
                using (HttpClient httpClient = new HttpClient()){
                    httpClient.Timeout = Timeout.InfiniteTimeSpan;

                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", access_code);
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "CoFlows");

                    var res = httpClient.GetAsync("https://api.github.com/user/emails").Result;

                    var data = res.Content.ReadAsStringAsync().Result;

                    var d = JArray.Parse(data);
                    email = d[0]["email"].ToString();
                }
            }

            string id = "QuantAppSecure_" + email.ToLower().Replace('@', '.').Replace(':', '.');

            var quser = QuantApp.Kernel.User.FindUser(id);

            if (quser == null)
            {
                var user = UserRepository.CreateUser(System.Guid.NewGuid().ToString(), "QuantAppSecure");

                user.FirstName = "";
                user.LastName  = "";
                user.Email     = email.ToLower();

                user.TenantName = id;

                quser = QuantApp.Kernel.User.FindUser(id);
                QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup("Public");
                group.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);

                QuantApp.Kernel.Group gp = QuantApp.Kernel.Group.FindGroup(groupid);
                if (gp != null)
                {
                    gp.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);
                }
            }


            if (String.IsNullOrEmpty(quser.Secret))
            {
                var secret_key = QuantApp.Engine.Code.GetMd5Hash(quser.ID);
                quser.Secret = secret_key;
            }

            var sessionKey = System.Guid.NewGuid().ToString();

            AccountController.sessionKeys.TryAdd(sessionKey, quser.Secret);
            Response.Cookies.Append("coflows", sessionKey, new CookieOptions()
            {
                Expires = DateTime.Now.AddHours(24)
            });

            var claims = new[]
            {
                new Claim(ClaimTypes.Email, quser.Email)
            };

            var key   = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "coflows-ce",
                audience: "coflows-ce",
                claims: claims,
                expires: DateTime.Now.AddDays(10),
                signingCredentials: creds);


            Response.Redirect("/authentication/token/" + new JwtSecurityTokenHandler().WriteToken(token), true);
        }
Example #9
0
        public static string QID(this IPrincipal user)
        {
            if (user == null)
            {
                return(null);
            }

            var identity = user.Identity as ClaimsIdentity;

            if (identity != null)
            {
                var email = identity.Claims.SingleOrDefault(c => c.Type.Equals(ClaimTypes.Email, StringComparison.OrdinalIgnoreCase));
                if (email == null)
                {
                    email = identity.Claims.SingleOrDefault(c => c.Type.Equals("emails", StringComparison.OrdinalIgnoreCase));
                }

                if (email != null && !string.IsNullOrEmpty(email.Value))
                {
                    AzureAD.Sync();

                    var id    = "QuantAppSecure_" + email.Value.ToLower().Replace('@', '.').Replace(':', '.');
                    var quser = QuantApp.Kernel.User.FindUser(id);
                    if (quser == null)
                    {
                        var nuser = UserRepository.CreateUser(System.Guid.NewGuid().ToString(), "QuantAppSecure");

                        var firstName = identity.Claims.SingleOrDefault(c => c.Type.Equals(ClaimTypes.GivenName, StringComparison.OrdinalIgnoreCase));
                        var lastName  = identity.Claims.SingleOrDefault(c => c.Type.Equals(ClaimTypes.Surname, StringComparison.OrdinalIgnoreCase));

                        nuser.FirstName = firstName != null ? firstName.Value : "No first name";
                        nuser.LastName  = lastName != null ? lastName.Value : "No last name";
                        nuser.Email     = email.Value.ToLower();

                        nuser.TenantName = id;
                        nuser.Hash       = QuantApp.Kernel.Adapters.SQL.Factories.SQLUserFactory.GetMd5Hash(System.Guid.NewGuid().ToString());

                        nuser.Secret = QuantApp.Engine.Code.GetMd5Hash(id);

                        quser = QuantApp.Kernel.User.FindUser(id);
                        QuantApp.Kernel.Group group = QuantApp.Kernel.Group.FindGroup("Public");
                        group.Add(quser, typeof(QuantApp.Kernel.User), AccessType.Invited);

                        // QuantApp.Kernel.Group gp = GroupRepository.FindByProfile(profile);
                        var defGroupId           = Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"] != null ? Program.config["Server"]["OAuth"]["AzureAdB2C"]["DefaultGroupId"].ToString() : "";
                        QuantApp.Kernel.Group gp = Group.FindGroup(defGroupId);
                        if (gp != null)
                        {
                            gp.Add(quser, typeof(QuantApp.Kernel.User), AccessType.View);
                        }
                    }
                    return(id);
                }


                else if (user.Identity.Name != null && user.Identity.Name.StartsWith("QuantAppSecure_"))
                {
                    return(user.Identity.Name);
                }
            }

            return(null);
        }