Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Security.Cryptography;
- using System.Text;
- public class AAAA
- {
- public string CheckHash(params string[] values)
- {
- //i parametri devono essere ordinati allo stesso modo altrimenti l'hash viene fuori diverso
- string secret = "secret123!";
- //https://msdn.microsoft.com/it-it/library/system.security.cryptography.sha1managed.computehash(v=vs.110).aspx
- using (SHA1Managed sha1 = new SHA1Managed())
- {
- var hashNew = sha1.ComputeHash(Encoding.UTF8.GetBytes(string.Join("", values) + secret)); //Calcola il valore hash della matrice di byte
- var sb = new StringBuilder(hashNew.Length * 2);
- foreach (byte b in hashNew)
- {
- // "x2" restituisce una stringa lowercase
- sb.Append(b.ToString("x2"));
- }
- return sb.ToString();
- }
- }
- }
- private const int RESULT_OK = 0;
- private const int RESULT_ERROR = 1;
- private const int RESULT_CUSTOM = 2;
- /*
- Codici errori
- -1 -> Errore del server
- 0 -> OK
- 1 -> Invalid Hash!
- 2 -> User not found
- 3 -> Too many attempts
- 4 -> SMS Send error
- 5 -> Numero non validato
- 6 -> Utente già esistente
- 7 -> Errore MOR
- 8 -> Impossibile verificare la transazione
- 9 -> Impossibile ricaricare il conto (payment non scritto su MOR)
- 10 -> No did available
- 11 -> Voucher Redeem error MOR
- 12 -> Impossibile rimuovere la deviazione
- 13 -> Impossibile impostare la deviazione
- */
- private static bool SMSEnabled
- {
- get { return bool.Parse(ConfigurationManager.AppSettings["sms_enabled"]); }
- }
- public List<CountryResult> GetCountries(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string prefix = nv["prefix"];
- string hash = nv["hash"];
- bool loadPrefix = prefix == "1";
- if (!CheckHash(hash, prefix))
- return null;
- using (DbEntities db = new DbEntities())
- {
- return db.Countries.OrderBy(c => c.CountryName).Select(c =>
- new CountryResult
- {
- Id = c.CountryId,
- Name = c.CountryName,
- Prefix = loadPrefix ? "+" + c.Prefix : ""
- }).ToList();
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "GetCountries", param);
- return null;
- }
- }
- public RegisterResult Register(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string number = nv["number"];
- string prefix = nv["prefix"];
- string hash = nv["hash"];
- if (!CheckHash(hash, number, prefix))
- return new RegisterResult { Result = RESULT_ERROR, Message = 1 };
- int codice = GeneraCodice();
- string token;
- using (DbEntities db = new DbEntities())
- {
- Users u = db.Users.FirstOrDefault(c => c.Prefix == prefix && c.Number == number);
- if (u == null)
- {
- u = new Users();
- u.UserId = Guid.NewGuid();
- u.Prefix = prefix;
- u.Number = number;
- u.OTPRequest = 1;
- u.CreatedDate = DateTime.Now.ToCentralEuropeTime();
- u.IsActive = false;
- db.Users.Add(u);
- }
- else
- {
- u.OTPRequest++;
- if (u.OTPRequest > 5 && SMSEnabled)
- {
- MailSender.InviaErrore("Superati i 5 tentativi di invio SMS di registrazione", "Register", string.Format("Numero: {0}-{1}", prefix, number));
- return new RegisterResult { Result = RESULT_ERROR, Message = 3 };
- }
- }
- u.OTP = codice;
- db.SaveChanges();
- token = u.UserId.ToString();
- if (SMSEnabled && !SMSSender.Send(u.UserId, db, prefix + number, codice))
- return new RegisterResult { Result = RESULT_ERROR, Message = 4 };
- }
- RegisterResult result = new RegisterResult();
- result.Result = RESULT_OK;
- result.Message = 0;
- result.Token = token;
- result.Number = "+" + prefix + number;
- result.Prefix = "+" + prefix;
- return result;
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "Register", param);
- return new RegisterResult { Result = RESULT_ERROR, Message = -1 };
- }
- }
- public GenericResult ReSendSMS(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- int codice = GeneraCodice();
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- if (u.OTPRequest >= 5 && SMSEnabled)
- {
- MailSender.InviaErrore("Superati i 5 tentativi di reinvio SMS di registrazione", "ReSendSMS", string.Format("Numero: {0}-{1}", u.Prefix, u.Number));
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 3 };
- }
- u.OTPRequest++;
- u.OTP = codice;
- db.SaveChanges();
- if (SMSEnabled && !SMSSender.Send(u.UserId, db, u.Prefix + u.Number, codice))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 4 };
- }
- GenericResult result = new GenericResult();
- result.Result = RESULT_OK;
- result.Message = "";
- return result;
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "ReSendSMS", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- public RegistrationCompleteResult ConfirmCode(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string code = nv["code"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, code))
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 1 };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- Users u = db.Users.Include("UserInfo").FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 2 };
- if (SMSEnabled && u.OTP != int.Parse(code))
- return new RegistrationCompleteResult { Result = RESULT_CUSTOM };
- u.NumberConfirmedDate = DateTime.Now.ToCentralEuropeTime();
- db.SaveChanges();
- RegistrationCompleteResult result = new RegistrationCompleteResult();
- result.Result = RESULT_OK;
- result.IsActive = u.IsActive;
- if (result.IsActive)
- {
- //è vero in caso di re-registrazione, in tal caso mando questi dati e salto la richiesta dei dati personaliabtoPhone
- result.Secret = u.UserInfo.DevicePassword.DecryptFromStorage().EncryptForPhone();
- result.Extension = u.UserInfo.DeviceExtension;
- result.Domain = ConfigurationManager.AppSettings["sip_domain"];
- result.DevicePin = u.UserInfo.DevicePin.EncryptForPhone();
- result.FreeCall = u.UserInfo.FreeCall;
- }
- return result;
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "ConfirmCode", param);
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
- }
- }
- public RegistrationCompleteResult SetUserInfo(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string nome = nv["nome"];
- string cognome = nv["cognome"];
- string email = nv["email"];
- string nazione = nv["nazione"]; //id numerico
- string citta = nv["citta"];
- string cap = nv["cap"];
- string codiceAffiliazione = nv["codice"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, nome, cognome, email, nazione, citta, cap))
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 1 };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 2 };
- if (!u.NumberConfirmedDate.HasValue)
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 5 };
- if (u.IsActive)
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 6 };
- //creo l'utente su MOR
- MOR.User morUser = new MOR.User(u.Prefix + u.Number, email, nome, cognome, nazione, citta, cap, true);
- MOR mor = new MOR(u.UserId);
- if (!mor.CreateUser(morUser))
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 7 };
- u.IsActive = true;
- u.RegistrationCompletedDate = DateTime.Now.ToCentralEuropeTime();
- u.UserInfo = new UserInfo();
- u.UserInfo.MorUserId = int.Parse(morUser.UserId);
- u.UserInfo.City = citta;
- u.UserInfo.CountryId = int.Parse(nazione);
- u.UserInfo.Email = email;
- u.UserInfo.FirstName = nome;
- u.UserInfo.LastName = cognome;
- u.UserInfo.Zip = cap;
- u.UserInfo.Username = morUser.username;
- u.UserInfo.Password = morUser.password.EncryptForStorage();
- u.UserInfo.DeviceId = morUser.device.id;
- u.UserInfo.DeviceExtension = morUser.device.extension;
- u.UserInfo.DevicePassword = morUser.device.secret.EncryptForStorage();
- u.UserInfo.DevicePin = morUser.device.pin;
- u.UserInfo.FreeCall = codiceAffiliazione == "FREE";
- db.SaveChanges();
- var result = new RegistrationCompleteResult();
- result.Secret = morUser.device.secret.EncryptForPhone();
- result.DevicePin = morUser.device.pin.EncryptForPhone();
- result.Extension = morUser.device.extension;
- result.Domain = ConfigurationManager.AppSettings["sip_domain"];
- result.Result = RESULT_OK;
- result.FreeCall = u.UserInfo.FreeCall;
- return result;
- }
- }
- catch (DbEntityValidationException dbEx)
- {
- string errorMessage = "";
- foreach (var validationErrors in dbEx.EntityValidationErrors)
- foreach (var validationError in validationErrors.ValidationErrors)
- errorMessage += string.Format("Property: {0} Error: {1}<br>", validationError.PropertyName, validationError.ErrorMessage);
- MailSender.InviaErrore(new Exception(errorMessage), "SetUserInfo", param);
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "SetUserInfo", param);
- return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
- }
- }
- public List<CallHistoryResult> CallHistory(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return null;
- int morUserId;
- string myNumber;
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return null;
- morUserId = u.MorUserId;
- myNumber = u.DeviceExtension;
- }
- MOR mor = new MOR(userId);
- List<MOR.Call> calls = mor.GetUserCalls(morUserId);
- if (calls == null)
- return null;
- List<CallHistoryResult> result = new List<CallHistoryResult>(calls.Count);
- foreach (MOR.Call call in calls)
- {
- bool isOutgoing = call.Source == myNumber;
- CallHistoryResult c = new CallHistoryResult();
- c.Datetime = call.CallDate.ToString("yyyy-MM-dd HH:mm:ss");
- c.IsOutgoing = isOutgoing;
- c.Number = isOutgoing ? call.Destination : call.Source;
- result.Add(c);
- }
- return result;
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "CallHistory", param);
- return null;
- }
- }
- public GenericResult UserCredit(Stream data)
- {
- string param = string.Empty;
- try
- {
- SchedulerManager scheduler = new SchedulerManager();
- scheduler.Start();
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return new GenericResult { Result = RESULT_ERROR, Message = "-" };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, Message = "-" };
- MOR mor = new MOR(u.UserId);
- string balance = mor.GetUserBalance(u.Username);
- return new GenericResult { Result = RESULT_OK, Message = balance ?? "-" };
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "UserCredit", param);
- return new GenericResult { Result = RESULT_ERROR, Message = "-" };
- }
- }
- public GenericResult PaypalPayment(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string currencyCode = nv["code"];
- string amount = nv["amount"];
- string paymentId = nv["transaction"];
- string createDate = nv["date"];
- string type = nv["type"];
- string hash = nv["hash"];
- string did_durata = nv["durata"]; //no hash
- string did_country_prefix = nv["country"]; //no hash
- if (!CheckHash(hash, token, currencyCode, amount, paymentId, createDate, type))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- Transazioni t = new Transazioni();
- t.PaymentId = paymentId;
- t.CreateTime = createDate;
- t.UserId = u.UserId;
- t.Amount = amount;
- t.Currency = currencyCode;
- t.Type = type;
- t.Verified = false;
- db.Transazioni.Add(t);
- db.SaveChanges();
- if (!VerificaTransazione(paymentId))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 8 };
- MOR mor = new MOR(u.UserId);
- if (type == "credit")
- {
- //ricarico il conto
- if (!mor.UpdateUserBalance(u.Username, u.MorUserId.ToString(), currencyCode, amount, "paypal", paymentId))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 9 };
- }
- else
- {
- //associo un did del paese scelto all'utente
- string did = mor.AssignDidToDevice(did_country_prefix, u.DeviceId.ToString(), u.Username);
- if (did == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 10 };
- DateTime date = DateTime.Now.ToCentralEuropeTime();
- Did d = new Did();
- d.Number = did;
- d.Enabled = true;
- d.EndDate = date.Date.AddDays(double.Parse(did_durata) + 1).AddMinutes(-1);
- d.PaymentId = paymentId;
- d.StartDate = date;
- d.UserId = userId;
- d.Prefix = did_country_prefix;
- db.Did.Add(d);
- db.SaveChanges();
- }
- return new GenericResult { Result = RESULT_OK, Message = "" };
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "PaypalPayment", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- public GenericResult RedeemVoucher(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string code = nv["code"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, code))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- MOR mor = new MOR(u.UserId);
- //ricarico il conto
- string voucher_amount;
- if (!mor.UseVoucher(u.MorUserId.ToString(), code, out voucher_amount))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 11 };
- string balance = mor.GetUserBalance(u.Username);
- return new GenericResult { Result = RESULT_OK, Message = voucher_amount + "|" + balance };
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "RedeemVoucher", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- public List<FreeDidResult> FreeDidList(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return null;
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return null;
- MOR mor = new MOR(userId);
- List<string> dids = mor.GetFreeDid();
- List<Countries> filteredCountries = new List<Countries>();
- List<Countries> countries = db.Countries.ToList();
- foreach (string did in dids)
- {
- var temp = countries.FirstOrDefault(c => did.StartsWith(c.Prefix));
- if (temp != null && filteredCountries.All(c => c.CountryId != temp.CountryId))
- filteredCountries.Add(temp);
- }
- if (filteredCountries.Count == 0)
- return null;
- return filteredCountries.Select(c => new FreeDidResult { CountryId = c.CountryId, CountryName = c.CountryName, Prefix = c.Prefix }).ToList();
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "FreeDidList", param);
- return null;
- }
- }
- public List<DidListResult> UserDidList(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return null;
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- var result = (from did in db.Did
- join country in db.Countries on did.Prefix equals country.Prefix
- where did.Enabled && did.UserId.Equals(userId)
- select new { did.Number, did.EndDate, country.CountryName }).ToList();
- return result.Select(c => new DidListResult { Number = c.Number, Scadenza = c.EndDate.ToString("yyyy-MM-dd HH:mm"), Country = c.CountryName }).ToList();
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "UserDidList", param);
- return null;
- }
- }
- public SettingsResult Settings(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token))
- return new SettingsResult { Result = RESULT_ERROR, Message = 1 };
- Guid userId = Guid.Parse(token);
- int deviceId;
- bool didsAvailable;
- string myNumber;
- using (DbEntities db = new DbEntities())
- {
- var u = db.Users.Where(c => c.UserId.Equals(userId) && c.IsActive).Select(c => new { c.UserInfo.DeviceId, c.Prefix, c.Number }).FirstOrDefault();
- if (u == null)
- return new SettingsResult { Result = RESULT_ERROR, Message = 2 };
- deviceId = u.DeviceId;
- myNumber = u.Prefix + u.Number;
- didsAvailable = db.Did.Any(c => c.Enabled && c.UserId.Equals(userId));
- }
- MOR mor = new MOR(userId);
- string forwardNumber = mor.GetCallFlowNumber(deviceId.ToString());
- SettingsResult result = new SettingsResult();
- result.Result = RESULT_OK;
- result.DeviazioneStandard = !string.IsNullOrEmpty(forwardNumber);
- if (result.DeviazioneStandard)
- result.DeviazioneNumero = forwardNumber.StartsWith("+") ? forwardNumber : "+" + forwardNumber;
- result.DidEnabled = didsAvailable && forwardNumber.Replace("+", "") == myNumber;
- result.DidAvailable = didsAvailable;
- return result;
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "Settings", param);
- return new SettingsResult { Result = RESULT_ERROR, Message = -1 };
- }
- }
- public GenericResult EditCallFlow(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string forward = nv["number"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, forward))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- Guid userId = Guid.Parse(token);
- int deviceId;
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- deviceId = u.DeviceId;
- }
- MOR mor = new MOR(userId);
- if (string.IsNullOrEmpty(forward))
- {
- //rimuovo la deviazione
- if (!mor.RemoveForward(deviceId.ToString()))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 12 };
- }
- else
- {
- //aggiungo la deviazione
- if (!mor.SetForward(deviceId.ToString(), forward))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 13 };
- }
- return new GenericResult { Result = RESULT_OK, Message = forward };
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "EditCallFlow", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- public GenericResult VerifyNumber(Stream data)
- {
- //per i quickforward
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string number = nv["number"];
- string code = nv["code"];
- string hash = nv["hash"];
- bool firstStep = string.IsNullOrEmpty(code);
- bool isValidHash = firstStep ? CheckHash(hash, token, number) : CheckHash(hash, token, code);
- if (!isValidHash)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- if (firstStep)
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- {
- MailSender.InviaErrore("Uso senza essere registrati del metodo di invio codice conferma su inserimento Deviazioni", "VerifyNumber", token, number, code);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- }
- int codice = GeneraCodice();
- NumberVerified num = new NumberVerified();
- num.CreatedDate = DateTime.Now.ToCentralEuropeTime();
- if (number.StartsWith("+"))
- num.Number = number.Replace("+", "");
- else
- num.Number = number;
- num.OTP = codice;
- num.Used = false;
- num.UserId = userId;
- if (SMSEnabled)
- {
- //controllo che per la giornata odierna non ci siano troppi tentativi
- DateTime now = DateTime.Now.ToCentralEuropeTime();
- int day = now.Day;
- int month = now.Month;
- int year = now.Year;
- if (db.NumberVerified.Count(c => c.UserId.Equals(userId) && c.CreatedDate.Day == day && c.CreatedDate.Month == month && c.CreatedDate.Year == year) >= 5)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 3 };
- if (!SMSSender.Send(u.UserId, db, number, codice))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 4 };
- }
- db.NumberVerified.Add(num);
- db.SaveChanges();
- }
- else
- {
- int otp = int.Parse(code);
- NumberVerified num = SMSEnabled ?
- db.NumberVerified.FirstOrDefault(c => c.UserId.Equals(userId) && c.OTP == otp && !c.Used) :
- db.NumberVerified.OrderByDescending(c => c.Progressivo).FirstOrDefault(c => c.UserId.Equals(userId));
- if (num == null)
- return new GenericResult { Result = RESULT_CUSTOM };
- num.Used = true;
- db.SaveChanges();
- return new GenericResult { Result = RESULT_OK, Message = "+" + num.Number };
- }
- }
- return new GenericResult { Result = RESULT_OK, Message = "" };
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "VerifyNumber", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- public RatesResult Rates(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string number = nv["number"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, number))
- return new RatesResult { Result = RESULT_ERROR };
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new RatesResult { Result = RESULT_ERROR };
- MOR mor = new MOR(userId);
- string result = mor.GetRates(u.Username, number);
- if (result == null)
- return new RatesResult { Result = RESULT_ERROR };
- //0.987#Lithuania#370->prefix con altre cifre
- string[] rate = result.Split('#');
- return new RatesResult { Result = RESULT_OK, Cost = rate[0].FormatCurrency(), CountryName = rate[1] };
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "Rates", param);
- return new RatesResult { Result = RESULT_ERROR };
- }
- }
- public GenericResult MatchContact(Stream data)
- {
- string param = string.Empty;
- try
- {
- param = new StreamReader(data).ReadToEnd();
- NameValueCollection nv = HttpUtility.ParseQueryString(param);
- string token = nv["token"];
- string prefix = nv["prefix"];
- string ids = nv["ids"];
- string numbers = nv["numbers"];
- string hash = nv["hash"];
- if (!CheckHash(hash, token, prefix))
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
- prefix = prefix.Replace("+", "");
- Guid userId = Guid.Parse(token);
- using (DbEntities db = new DbEntities())
- {
- UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
- if (u == null)
- return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
- string[] _ids = ids.Split(',');
- string[] temp = numbers.Split(','); //devo ripulire i numeri da * + () e spazi
- List<string> _numbers = new List<string>(temp.Length);
- foreach (var num in temp)
- {
- _numbers.Add(new string(num.Where(char.IsDigit).ToArray()));
- }
- List<Contact> contatti = new List<Contact>();
- for (int i = 0; i < _ids.Length; i++)
- {
- var contatto = contatti.FirstOrDefault(c => c.Id.Equals(_ids[i]));
- if (contatto != null)
- contatto.Number.Add(_numbers[i]);
- else
- contatti.Add(new Contact(_ids[i], _numbers[i]));
- }
- List<string> dbNumber = db.Users.Select(c => c.Prefix + c.Number).ToList();
- foreach (var contact in contatti)
- {
- if (dbNumber.Any(c => contact.Number.Contains(c) || contact.Number.Select(d => prefix + d).Contains(c)))
- contact.Matched = true;
- }
- if (contatti.Count == 0)
- return new GenericResult { Result = RESULT_OK, Message = "" };
- return new GenericResult { Result = RESULT_OK, Message = string.Join(",", contatti.Where(c => c.Matched).Select(c => c.Id)) };
- }
- }
- catch (Exception ex)
- {
- MailSender.InviaErrore(ex, "MatchContact", param);
- return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
- }
- }
- private class Contact
- {
- public string Id { get; private set; }
- public List<string> Number { get; private set; }
- public bool Matched { get; set; }
- public Contact(string id, string number)
- {
- Id = id;
- Number = new List<string>();
- Number.Add(number);
- }
- }
- private bool VerificaTransazione(string paymentId)
- {
- //todo: verificare pagamento
- //https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
- return true;
- /* try
- {
- //salvo la transazione prima della verifica
- Transazioni tr = new Transazioni();
- tr.UserId = userId;
- tr.Codice = response_id;
- tr.Response = paypalResponse;
- tr.Data = DateTime.Now;
- tr.Verificata = false;
- tr.CreditPackId = creditPackId;
- db.AddToTransazioni(tr);
- db.SaveChanges();
- //chiedo a paypal i dati della transazione e verifico le condizioni di cui sopra
- // Get a reference to the config section in Web.Config
- var config = ConfigManager.Instance.GetProperties();
- // Use OAuthTokenCredential to request an access token from PayPal
- var accessToken = new OAuthTokenCredential(config).GetAccessToken();
- var apiContext = new APIContext(accessToken);
- // Initialize the apiContext's configuration with the default configuration for this application.
- apiContext.Config = ConfigManager.Instance.GetProperties();
- var payment = Payment.Get(apiContext, response_id); //response_id è il codice della transazione
- bool state = payment.state == "approved";
- string totale_da_pagare = db.Crediti.First(c => c.CreditPackId == creditPackId).CreditPrice;
- var transaction = payment.transactions.FirstOrDefault(c => c.amount != null && c.amount.total == totale_da_pagare && c.amount.currency == "EUR");
- string transactionId = null;
- bool related_resources = false;
- if (transaction != null)
- {
- tr.Amount = transaction.amount.total;
- tr.Currency_code = transaction.amount.currency;
- var rr = transaction.related_resources.FirstOrDefault(c => c.sale != null && c.sale.state == "completed");
- if (rr != null)
- {
- related_resources = true;
- transactionId = rr.sale.id;
- }
- }
- bool verificata = state && transaction != null && related_resources;
- tr.PaymentJson = payment.ConvertToJson();
- tr.Timestamp = payment.create_time;
- tr.Token = transactionId;
- tr.Verificata = verificata;
- db.SaveChanges();
- return verificata;
- }
- catch (PayPal.PayPalException ex)
- {
- MailSender.InoltraErrore(ex, "VerificaTransazione", String.Format("response_id: {0} - fullResponse: {1}", response_id, paypalResponse));
- return false;
- }*/
- }
- private int GeneraCodice()
- {
- Random r = new Random();
- return r.Next(10000, 99999);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement