// POST api/CustomLogin
        public HttpResponseMessage Post(ChangePassRequest changeRequest)
        {
            string shardKey = Sharding.FindShard(User);
            // NEED TO RECHECK CONTEXT MUST DETERMINE COMPANY -> MUST FIND CORRECT DataBase
            mpbdmContext <Guid> context = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, new Guid(shardKey), WebApiConfig.ShardingObj.connstring);
            Account             account = context.Accounts.Include("User").Where(a => a.User.Email == changeRequest.email).SingleOrDefault();

            if (account != null)
            {
                byte[] incoming = CustomLoginProviderUtils.hash(changeRequest.oldpass, account.Salt);

                if (CustomLoginProviderUtils.slowEquals(incoming, account.SaltedAndHashedPassword))
                {
                    if (changeRequest.password == changeRequest.repass)
                    {
                        byte[] newpass = CustomLoginProviderUtils.hash(changeRequest.password, account.Salt);
                        account.SaltedAndHashedPassword = newpass;
                        context.SaveChanges();
                        return(this.Request.CreateResponse(HttpStatusCode.Created));
                    }
                    return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Passes don't match"));
                }
            }
            return(this.Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid email or password"));
        }
Beispiel #2
0
        public async Task <HttpResponseMessage> Post(string contactId)
        {
            string shardKey        = Sharding.FindShard(User);
            mpbdmContext <Guid> db = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, new Guid(shardKey), WebApiConfig.ShardingObj.connstring);
            // Security issue check company
            Contacts contact = db.Set <Contacts>().Include("Groups").Where(s => s.Id == contactId && s.Groups.CompaniesID == shardKey).FirstOrDefault();

            if (contact == null)
            {
                this.Request.CreateResponse(HttpStatusCode.BadRequest, "Contact doesnt't exist!");
            }

            CloudStorageAccount acc            = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["Azure"].ConnectionString);
            CloudBlobClient     blobClient     = acc.CreateCloudBlobClient();
            CloudBlobContainer  photoContainer = blobClient.GetContainerReference("images");

            await photoContainer.CreateIfNotExistsAsync();

            var provider = new AzureBlobMultipartFormDataStreamProvider(photoContainer);

            await this.Request.Content.ReadAsMultipartAsync(provider);

            foreach (var file in provider.FileData)
            {
                //the LocalFileName is going to be the absolute Uri of the blob (see GetStream)
                //use it to get the blob info to return to the client
                var blob = await photoContainer.GetBlobReferenceFromServerAsync(file.LocalFileName);

                var fileNameGuid = Guid.NewGuid().ToString();
                // Copy to get new URL
                ICloudBlob newBlob = null;
                if (blob is CloudBlockBlob)
                {
                    newBlob = photoContainer.GetBlockBlobReference(fileNameGuid);
                }
                else
                {
                    newBlob = photoContainer.GetPageBlobReference(fileNameGuid);
                }
                //Initiate blob copy
                await newBlob.StartCopyFromBlobAsync(blob.Uri);

                ////Now wait in the loop for the copy operation to finish
                //while (true)
                //{
                //    newBlob.FetchAttributes();
                //    if (newBlob.CopyState.Status != CopyStatus.Pending)
                //    {
                //        break;
                //    }
                //    //Sleep for a second may be
                //    System.Threading.Thread.Sleep(1000);
                //}
                blob.Delete();

                await newBlob.FetchAttributesAsync();

                string url = newBlob.Uri.ToString();
                //// DELETING ANY OLD BLOBS
                //if (contact.ImageUrl != null)
                //{
                //    var oldBlob = photoContainer.GetBlobReferenceFromServer(contact.ImageUrl);
                //    oldBlob.Delete();
                //}
                ////////////////////////////
                //contact.ImageUrl = url;
                contact.ImageUrl = newBlob.Name.ToString();

                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "CannotSaveChanges!"));
                }
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> Post()
        {
            string shardKey        = Sharding.FindShard(User);
            mpbdmContext <Guid> db = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, new Guid(shardKey), WebApiConfig.ShardingObj.connstring);
            // Security issue check company
            var   user       = User as ServiceUser;
            Users userEntity = db.Set <Users>().Where(s => s.Id == user.Id).FirstOrDefault();

            if (userEntity == null)
            {
                this.Request.CreateResponse(HttpStatusCode.BadRequest, "User doesnt't exist!");
            }

            CloudStorageAccount acc            = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["Azure"].ConnectionString);
            CloudBlobClient     blobClient     = acc.CreateCloudBlobClient();
            CloudBlobContainer  photoContainer = blobClient.GetContainerReference("images");
            await photoContainer.CreateIfNotExistsAsync();

            var provider = new AzureBlobMultipartFormDataStreamProvider(photoContainer);

            await this.Request.Content.ReadAsMultipartAsync(provider);

            foreach (var file in provider.FileData)
            {
                var blob = await photoContainer.GetBlobReferenceFromServerAsync(file.LocalFileName);

                var        fileNameGuid = Guid.NewGuid().ToString();
                ICloudBlob newBlob      = null;
                if (blob is CloudBlockBlob)
                {
                    newBlob = photoContainer.GetBlockBlobReference(fileNameGuid);
                }
                else
                {
                    newBlob = photoContainer.GetPageBlobReference(fileNameGuid);
                }
                await newBlob.StartCopyFromBlobAsync(blob.Uri);

                blob.Delete();
                await newBlob.FetchAttributesAsync();

                string url = newBlob.Uri.ToString();

                //// DELETING ANY OLD BLOBS
                //if (userEntity.ImageUrl != null)
                //{
                //    var oldBlob = photoContainer.GetBlobReferenceFromServer(userEntity.ImageUrl);
                //    oldBlob.Delete();
                //}
                ////////////////////////////
                // UPDATE imageUrl of user
                //userEntity.ImageUrl = url;
                userEntity.ImageUrl = newBlob.Name.ToString();

                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "CannotSaveChanges!"));
                }
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Beispiel #4
0
        public async Task <HttpResponseMessage> Post(string groupsId)
        {
            CloudStorageAccount acc            = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["Azure"].ConnectionString);
            CloudBlobClient     blobClient     = acc.CreateCloudBlobClient();
            CloudBlobContainer  photoContainer = blobClient.GetContainerReference("temp");

            await photoContainer.CreateIfNotExistsAsync();

            var provider = new AzureBlobMultipartFormDataStreamProvider(photoContainer);

            await this.Request.Content.ReadAsMultipartAsync(provider);

            //var photos = new List<PhotoViewModel>();

            foreach (var file in provider.FileData)
            {
                //the LocalFileName is going to be the absolute Uri of the blob (see GetStream)
                //use it to get the blob info to return to the client
                var blob = await photoContainer.GetBlobReferenceFromServerAsync(file.LocalFileName);

                await blob.FetchAttributesAsync();

                string url = blob.Uri.ToString();
                //provider.GetStream(this.RequestContext);
                //FileStream fs = new FileStream();
                //blob.DownloadToStream(fs);


                //FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read);
                //HttpClient cl = new HttpClient();
                Stream ss = new MemoryStream();
                blob.DownloadToStream(ss);

                HSSFWorkbook templateWorkbook = new HSSFWorkbook(ss);

                HSSFSheet sheet = (HSSFSheet)templateWorkbook.GetSheet("Sheet1");

                string shardKey        = Sharding.FindShard(User);
                mpbdmContext <Guid> db = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, new Guid(shardKey), WebApiConfig.ShardingObj.connstring);
                for (int i = 1; true; i++)
                {
                    var row = sheet.GetRow(i);
                    if (row == null)
                    {
                        break;
                    }

                    Contacts cont = new Contacts();
                    cont.FirstName = row.GetCell(0).RichStringCellValue.String;
                    cont.LastName  = row.GetCell(1).RichStringCellValue.String;
                    cont.Email     = row.GetCell(2).RichStringCellValue.String;
                    cont.Phone     = row.GetCell(3).NumericCellValue.ToString();
                    cont.GroupsID  = (groupsId == "valueUndefined") ? row.GetCell(4).RichStringCellValue.String : groupsId;
                    cont.Id        = Guid.NewGuid().ToString();
                    cont.Deleted   = false;
                    cont.Visible   = true;

                    var chk = db.Set <Contacts>().Where(s => s.Email == cont.Email && s.LastName == cont.LastName && s.Groups.Companies.Id == shardKey).FirstOrDefault();
                    if (chk != null)
                    {
                        continue;
                    }

                    db.Set <Contacts>().Add(cont);
                }
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Propably the Foreign Key GroupId is wrong on some of your Contacts!!! Make sure the groupId exists!"));
                }
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Beispiel #5
0
        // POST api/CustomRegistration
        public HttpResponseMessage Post(RegistrationRequest registrationRequest)
        {
            if (!Regex.IsMatch(registrationRequest.email, "^([a-z.A-Z0-9]{1,})@([a-z]{2,}).[a-z]{2,}$"))
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid email!"));
            }
            else if (registrationRequest.password.Length < 8)
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password (at least 8 chars required)"));
            }

            // MUST FIND COMPANY BY EMAIL
            // CREATE a MULTISHARD COMMAND
            // SEARCH BY EMAIL
            mpbdmContext <Guid> context = null;
            Guid shardKey;

            using (MultiShardConnection conn = new MultiShardConnection(WebApiConfig.ShardingObj.ShardMap.GetShards(), WebApiConfig.ShardingObj.connstring))
            {
                using (MultiShardCommand cmd = conn.CreateCommand())
                {
                    // Get emailDomain
                    char[] papaki = new char[1];
                    papaki[0] = '@';
                    // SQL INJECTION SECURITY ISSUE
                    string emailDomain = registrationRequest.email.Split(papaki).Last();

                    // CHECK SCHEMA
                    cmd.CommandText      = "SELECT Id FROM [mpbdm].[Companies] WHERE Email LIKE '%" + emailDomain + "'";
                    cmd.CommandType      = CommandType.Text;
                    cmd.ExecutionOptions = MultiShardExecutionOptions.IncludeShardNameColumn;
                    cmd.ExecutionPolicy  = MultiShardExecutionPolicy.PartialResults;

                    using (MultiShardDataReader sdr = cmd.ExecuteReader())
                    {
                        bool res = sdr.Read();
                        if (res != false)
                        {
                            shardKey = new Guid(sdr.GetString(0));
                        }
                        else
                        {
                            if (registrationRequest.CompanyName == null || registrationRequest.CompanyAddress == null)
                            {
                                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Company under this email domain doesn't exist! To create a company with your registration please provide CompanyName and CompanyAddress parameters"));
                            }


                            Companies comp = new Companies();
                            comp.Id = Guid.NewGuid().ToString();

                            comp.Name    = registrationRequest.CompanyName;
                            comp.Address = registrationRequest.CompanyAddress;
                            comp.Email   = registrationRequest.email;
                            comp.Deleted = false;

                            // SHARDING Find where to save the new company
                            Shard shard = WebApiConfig.ShardingObj.FindRoomForCompany();
                            WebApiConfig.ShardingObj.RegisterNewShard(shard.Location.Database, comp.Id);
                            //Connect to the db registered above
                            shardKey = new Guid(comp.Id);
                            context  = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, shardKey, WebApiConfig.ShardingObj.connstring);
                            // Add to the db
                            context.Companies.Add(comp);
                            context.SaveChanges();
                        }
                    }
                }
            }
            //////////////////////////////////////////////////////////////////////

            // MUST RECHECK CORRECT DB!!!!!!!!!!!
            if (context == null)
            {
                context = new mpbdmContext <Guid>(WebApiConfig.ShardingObj.ShardMap, shardKey, WebApiConfig.ShardingObj.connstring);
            }
            Account account = null;

            var aa = context.Set <Account>();
            var bb = aa.Where(a => a.User.Email == registrationRequest.email);

            account = bb.FirstOrDefault();
            if (account != null)
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Email already exists"));
            }
            else
            {
                byte[] salt = CustomLoginProviderUtils.generateSalt();

                string compId = shardKey.ToString();

                Users newUser = new Users
                {
                    Id          = CustomLoginProvider.ProviderName + ":" + registrationRequest.email,
                    CompaniesID = compId,
                    FirstName   = registrationRequest.firstName,
                    LastName    = registrationRequest.lastName,
                    Email       = registrationRequest.email
                };

                Account newAccount = new Account
                {
                    Id = Guid.NewGuid().ToString(),
                    //Username = registrationRequest.username,
                    Salt = salt,
                    SaltedAndHashedPassword = CustomLoginProviderUtils.hash(registrationRequest.password, salt),
                    User = newUser
                };

                context.Users.Add(newUser);
                context.Accounts.Add(newAccount);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    var a = ex.InnerException;
                }
                return(this.Request.CreateResponse(HttpStatusCode.Created));
            }
        }