Esempio n. 1
0
func (c *Controller) ESignLogin() (string, error) {

	c.w.Header().Set("Access-Control-Allow-Origin", "*")

	var hash []byte
	loginCode := utils.RandSeq(20)

	RemoteAddr := utils.RemoteAddrFix(c.r.RemoteAddr)
	re := regexp.MustCompile(`(.*?):[0-9]+$`)
	match := re.FindStringSubmatch(RemoteAddr)
	if len(match) != 0 {
		RemoteAddr = match[1]
	}
	log.Debug("RemoteAddr %s", RemoteAddr)
	hash = utils.Md5(c.r.Header.Get("User-Agent") + RemoteAddr)
	log.Debug("hash %s", hash)

	err := c.DCDB.ExecSql(`DELETE FROM e_authorization WHERE hex(hash) = ?`, hash)
	if err != nil {
		return "", err
	}
	err = c.DCDB.ExecSql(`INSERT INTO e_authorization (hash, data) VALUES ([hex], ?)`, hash, loginCode)
	if err != nil {
		return "", err
	}
	log.Debug("loginCode %v", loginCode)
	return "\"" + loginCode + "\"", nil
}
Esempio n. 2
0
func (c *Controller) ESignUp() (string, error) {

	c.r.ParseForm()
	email := c.r.FormValue("email")
	password := c.r.FormValue("password")
	if len(password) > 50 || len(password) < 1 {
		return "", errors.New(c.Lang["invalid_pass"])
	}

	existsEmail, err := c.Single("SELECT id FROM e_users WHERE email = ?", email).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if existsEmail > 0 {
		return "", errors.New(c.Lang["exists_email"])
	}

	salt := utils.RandSeq(32)
	passAndSalt := utils.DSha256(password + salt)
	userId, err := c.ExecSqlGetLastInsertId("INSERT INTO e_users ( email, password, ip, salt ) VALUES ( ?, ?, ?, ? )", "id", email, passAndSalt, c.r.RemoteAddr, salt)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	c.sess.Set("e_user_id", userId)

	return utils.JsonAnswer("success", "success").String(), nil
}
Esempio n. 3
0
func (p *Parser) VotesNodeNewMiner() error {

	var votes [2]int64
	votesData, err := p.OneRow("SELECT user_id, votes_start_time, votes_0, votes_1 FROM votes_miners WHERE id = ?", p.TxMaps.Int64["vote_id"]).Int64()
	if err != nil {
		return p.ErrInfo(err)
	}
	log.Debug("votesData", votesData)
	log.Debug("votesData[user_id]", votesData["user_id"])
	minersData, err := p.OneRow("SELECT photo_block_id, photo_max_miner_id, miners_keepers, log_id FROM miners_data WHERE user_id = ?", votesData["user_id"]).String()
	log.Debug("minersData", minersData)
	// $votes_data['user_id'] - это юзер, за которого голосуют
	if err != nil {
		return p.ErrInfo(err)
	}

	votes[0] = votesData["votes_0"]
	votes[1] = votesData["votes_1"]
	// прибавим голос
	votes[p.TxMaps.Int64["result"]]++

	// обновляем голоса. При откате просто вычитаем
	err = p.ExecSql("UPDATE votes_miners SET votes_"+utils.Int64ToStr(p.TxMaps.Int64["result"])+" = ? WHERE id = ?", votes[p.TxMaps.Int64["result"]], p.TxMaps.Int64["vote_id"])
	if err != nil {
		return p.ErrInfo(err)
	}

	// логируем, чтобы юзер {$this->tx_data['user_id']} не смог повторно проголосовать
	err = p.ExecSql("INSERT INTO log_votes (user_id, voting_id, type) VALUES (?, ?, 'votes_miners')", p.TxMaps.Int64["user_id"], p.TxMaps.Int64["vote_id"])
	if err != nil {
		return p.ErrInfo(err)
	}

	// ID майнеров, у которых сохраняются фотки
	minersIds := utils.GetMinersKeepers(minersData["photo_block_id"], minersData["photo_max_miner_id"], minersData["miners_keepers"], true)

	log.Debug("minersIds", minersIds, len(minersIds))
	// данные для проверки окончания голосования

	minerData := new(MinerData)
	minerData.myMinersIds, err = p.getMyMinersIds()
	if err != nil {
		return p.ErrInfo(err)
	}
	minerData.adminUiserId, err = p.GetAdminUserId()
	if err != nil {
		return p.ErrInfo(err)
	}
	minerData.minersIds = minersIds
	minerData.votes0 = votes[0]
	minerData.votes1 = votes[1]
	minerData.minMinersKeepers = p.Variables.Int64["min_miners_keepers"]
	log.Debug("minerData.adminUiserId %v", minerData.adminUiserId)
	log.Debug("minerData.myMinersIds %v", minerData.myMinersIds)
	log.Debug("minerData.minersIds %v", minerData.minersIds)
	log.Debug("minerData.votes0 %v", minerData.votes0)
	log.Debug("minerData.votes1 %v", minerData.votes1)
	log.Debug("minerData.minMinersKeepers %v", minerData.minMinersKeepers)

	if p.minersCheckVotes1(minerData) || (minerData.votes0 > minerData.minMinersKeepers || int(minerData.votes0) == len(minerData.minersIds)) {
		// отмечаем, что голосование нодов закончено
		err = p.ExecSql("UPDATE votes_miners SET votes_end = 1, end_block_id = ? WHERE id = ?", p.BlockData.BlockId, p.TxMaps.Int64["vote_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
	}
	if p.minersCheckVotes1(minerData) || p.minersCheckMyMinerIdAndVotes0(minerData) {
		// отметим del_block_id всем, кто голосовал за данного юзера,
		// чтобы через N блоков по крону удалить бесполезные записи
		err = p.ExecSql("UPDATE log_votes SET del_block_id = ? WHERE voting_id = ? AND type = 'votes_miners'", p.BlockData.BlockId, p.TxMaps.Int64["vote_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
	}

	// если набрано >=X голосов "за", то пишем в БД, что юзер готов к проверке людьми
	// либо если набранное кол-во голосов= кол-ву майнеров (актуально в самом начале запуска проекта)
	if p.minersCheckVotes1(minerData) {
		err = p.ExecSql("INSERT INTO votes_miners ( user_id, type, votes_start_time ) VALUES ( ?, 'user_voting', ? )", votesData["user_id"], p.BlockData.Time)
		if err != nil {
			return p.ErrInfo(err)
		}

		// и отмечаем лицо как готовое участвовать в поиске дублей
		err = p.ExecSql("UPDATE faces SET status = 'used' WHERE user_id = ?", votesData["user_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
	} else if p.minersCheckMyMinerIdAndVotes0(minerData) {
		// если набрано >5 голосов "против" и мы среди тех X майнеров, которые копировали фото к себе
		// либо если набранное кол-во голосов = кол-ву майнеров (актуально в самом начале запуска проекта)
		facePath := fmt.Sprintf(*utils.Dir+"/public/face_%v.jpg", votesData["user_id"])
		profilePath := fmt.Sprintf(*utils.Dir+"/public/profile_%v.jpg", votesData["user_id"])

		faceRandName := ""
		profileRandName := ""
		// возможно фото к нам не было скопировано, т.к. хост был недоступен.
		if _, err := os.Stat(profilePath); os.IsNotExist(err) {
			faceRandName = ""
			profileRandName = ""
		} else if _, err := os.Stat(facePath); os.IsNotExist(err) {
			faceRandName = ""
			profileRandName = ""
		} else {
			faceRandName = utils.RandSeq(30)
			profileRandName = utils.RandSeq(30)

			// перемещаем фото в корзину, откуда по крону будем удалять данные
			err = utils.CopyFileContents(facePath, faceRandName)
			if err != nil {
				return p.ErrInfo(err)
			}
			err = os.Remove(facePath)
			if err != nil {
				return p.ErrInfo(err)
			}
			err = utils.CopyFileContents(profilePath, profileRandName)
			if err != nil {
				return p.ErrInfo(err)
			}
			err = os.Remove(profilePath)
			if err != nil {
				return p.ErrInfo(err)
			}

			// если в корзине что-то есть, то логируем
			// отсутствие файлов также логируем, т.к. больше негде, а при откате эти данные очень важны.
			logData, err := p.OneRow("SELECT * FROM recycle_bin WHERE user_id = ?", votesData["user_id"]).String()
			if err != nil {
				return p.ErrInfo(err)
			}
			if len(logData) > 0 {
				logId, err := p.ExecSqlGetLastInsertId("INSERT INTO log_recycle_bin ( user_id, profile_file_name, face_file_name, block_id, prev_log_id ) VALUES ( ?, ?, ?, ?, ? )", "log_id", logData["user_id"], logData["profile_file_name"], logData["face_file_name"], p.BlockData.BlockId, logData["log_id"])
				if err != nil {
					return p.ErrInfo(err)
				}
				err = p.ExecSql("UPDATE recycle_bin SET profile_file_name = ?, face_file_name = ?, log_id = ? WHERE user_id = ?", profileRandName, faceRandName, logId, logData["user_id"])
				if err != nil {
					return p.ErrInfo(err)
				}
			} else {
				err = p.ExecSql("INSERT INTO recycle_bin ( user_id, profile_file_name, face_file_name ) VALUES ( ?, ?, ? )", votesData["user_id"], profileRandName, faceRandName)
				if err != nil {
					return p.ErrInfo(err)
				}
			}
		}
	}

	return nil
}
Esempio n. 4
0
func (c *Controller) CashRequestOut() (string, error) {

	txType := "CashRequestOut"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	cashRequestsStatus := map[string]string{"my_pending": c.Lang["local_pending"], "pending": c.Lang["pending"], "approved": c.Lang["approved"], "rejected": c.Lang["rejected"]}

	jsonCurrencyWallets := ""
	var availableCurrency []int64
	// список отравленных нами запросов
	myCashRequests, err := c.GetAll("SELECT * FROM "+c.MyPrefix+"my_cash_requests WHERE to_user_id != ?", -1, c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// получаем список кошельков, на которых есть FC
	rows, err := c.Query(c.FormatQuery("SELECT amount, currency_id, last_update FROM wallets WHERE user_id = ? AND currency_id < 1000"), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var amount float64
		var currency_id, last_update int64
		err = rows.Scan(&amount, &currency_id, &last_update)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if currency_id == 1 {
			continue
		}
		profit, err := c.CalcProfitGen(currency_id, amount, c.SessUserId, last_update, timeNow, "wallets")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		amount += profit
		jsonCurrencyWallets += fmt.Sprintf(`"%d":["%s","%v"],`, currency_id, c.CurrencyList[currency_id], amount)
		availableCurrency = append(availableCurrency, currency_id)
	}
	jsonCurrencyWallets = jsonCurrencyWallets[:len(jsonCurrencyWallets)-1]
	//jsonCurrencyWallets = "\""
	log.Debug("jsonCurrencyWallets", jsonCurrencyWallets)
	code := utils.Md5(utils.RandSeq(50))
	hashCode := utils.DSha256(code)

	TemplateStr, err := makeTemplate("cash_request_out", "cashRequestOut", &cashRequestOutPage{
		Alert:               c.Alert,
		Lang:                c.Lang,
		CountSignArr:        c.CountSignArr,
		ShowSignData:        c.ShowSignData,
		UserId:              c.SessUserId,
		TimeNow:             timeNow,
		TxType:              txType,
		TxTypeId:            txTypeId,
		SignData:            "",
		CurrencyList:        c.CurrencyList,
		PaymentSystems:      c.PaymentSystems,
		JsonCurrencyWallets: jsonCurrencyWallets,
		CashRequestsStatus:  cashRequestsStatus,
		AvailableCurrency:   availableCurrency,
		MinPromisedAmount:   c.Variables.Int64["min_promised_amount"],
		MyCashRequests:      myCashRequests,
		Code:                string(code),
		HashCode:            string(hashCode),
		MaxLength:           200})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Esempio n. 5
0
func (c *Controller) ECheckSign() (string, error) {

	c.w.Header().Set("Access-Control-Allow-Origin", "*")

	c.r.ParseForm()
	userId := utils.StrToInt64(c.r.FormValue("user_id"))
	sign := []byte(c.r.FormValue("sign"))
	if !utils.CheckInputData(string(sign), "hex_sign") {
		return `{"result":"incorrect sign"}`, nil
	}
	if !utils.CheckInputData(userId, "int") {
		return `{"result":"incorrect user_id"}`, nil
	}

	var publicKey []byte
	if userId == 0 {
		n := []byte(c.r.FormValue("n"))
		e := []byte(c.r.FormValue("e"))
		if !utils.CheckInputData(n, "hex") {
			return `{"result":"incorrect n"}`, nil
		}
		if !utils.CheckInputData(e, "hex") {
			return `{"result":"incorrect e"}`, nil
		}
		log.Debug("n %v / e %v", n, e)
		publicKey = utils.MakeAsn1(n, e)
		log.Debug("publicKey %s", publicKey)
	}

	RemoteAddr := utils.RemoteAddrFix(c.r.RemoteAddr)
	re := regexp.MustCompile(`(.*?):[0-9]+$`)
	match := re.FindStringSubmatch(RemoteAddr)
	if len(match) != 0 {
		RemoteAddr = match[1]
	}
	log.Debug("RemoteAddr %s", RemoteAddr)
	hash := utils.Md5(c.r.Header.Get("User-Agent") + RemoteAddr)
	log.Debug("hash %s", hash)
	forSign, err := c.Single(`SELECT data FROM e_authorization WHERE hex(hash) = ?`, hash).String()
	if err != nil {
		return "{\"result\":0}", err
	}

	if userId > 0 {
		publicKey_, err := c.GetUserPublicKey(userId)
		publicKey = []byte(publicKey_)
		if err != nil {
			return "{\"result\":0}", err
		}
		if len(publicKey_) == 0 {
			return "{\"result\":0}", utils.ErrInfo("len(publicKey_) == 0")
		}
	} else {
		userId_, err := c.GetUserIdByPublicKey(publicKey)
		userId = utils.StrToInt64(userId_)
		publicKey = utils.HexToBin(publicKey)
		log.Debug("userId %d", userId)
		if err != nil {
			return "{\"result\":0}", err
		}
		if userId == 0 {
			return "{\"result\":0}", utils.ErrInfo("userId == 0")
		}
	}

	log.Debug("userId %v", userId)
	log.Debug("publicKey %x", publicKey)
	log.Debug("forSign %v", forSign)
	log.Debug("sign %s", sign)

	// проверим подпись
	resultCheckSign, err := utils.CheckSign([][]byte{[]byte(publicKey)}, forSign, utils.HexToBin(sign), true)
	if err != nil {
		return "{\"result\":0}", err
	}
	log.Debug("resultCheckSign %v", resultCheckSign)
	if resultCheckSign {
		// если это первый запрос, то создаем запись в табле users
		eUserId, err := c.Single(`SELECT id	FROM e_users WHERE user_id = ?`, userId).Int64()
		if err != nil {
			return "{\"result\":0}", err
		}
		if eUserId == 0 {
			eUserId, err = c.ExecSqlGetLastInsertId(`INSERT INTO e_users (user_id) VALUES (?)`, "id", userId)
			if err != nil {
				return "{\"result\":0}", err
			}
		}
		if len(c.r.FormValue("user_id")) > 0 {
			token := utils.RandSeq(30)
			err = c.ExecSql(`INSERT INTO e_tokens (token, user_id) VALUES (?, ?)`, token, eUserId)
			if err != nil {
				return "{\"result\":0}", err
			}
			log.Debug(`{"result":"1", "token":"` + token + `"}`)

			return `{"result":"1", "token":"` + token + `"}`, nil
		} else {
			c.sess.Set("e_user_id", eUserId)
			return `{"result":1}`, nil
		}
	} else {
		return "{\"result\":0}", nil
	}
}