예제 #1
0
func (c *Controller) GetChatMessages() (string, error) {

	c.r.ParseForm()
	first := c.r.FormValue("first")
	room := utils.StrToInt64(c.r.FormValue("room"))
	lang := utils.StrToInt64(c.r.FormValue("lang"))

	if first == "1" {
		chatIds[c.SessUserId] = []int{}
	}
	maxId, err := c.Single(`SELECT max(id) FROM chat`).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// удалим старое
	err = c.ExecSql(`DELETE FROM chat WHERE id < ?`, maxId-consts.CHAT_MAX_MESSAGES)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	ids := ""
	if len(chatIds[c.SessUserId]) > 0 {
		ids = `AND id NOT IN(` + strings.Join(utils.IntSliceToStr(chatIds[c.SessUserId]), ",") + `)`
	}
	var result string
	chatData, err := c.GetAll(`SELECT * FROM chat WHERE sign_time > ? AND room = ? AND lang = ?  `+ids+` ORDER BY sign_time DESC LIMIT `+utils.Int64ToStr(consts.CHAT_COUNT_MESSAGES), consts.CHAT_COUNT_MESSAGES, chatMinSignTime, room, lang)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for i := len(chatData) - 1; i >= 0; i-- {
		data := chatData[i]
		status := data["status"]
		message := data["message"]
		receiver := utils.StrToInt64(data["receiver"])
		sender := utils.StrToInt64(data["sender"])
		if status == "1" {
			// Если юзер хранит приватый ключ в БД, то сможем расшифровать прямо тут
			if receiver == c.SessUserId {
				privateKey, err := c.GetMyPrivateKey(c.MyPrefix)
				if err != nil {
					log.Error("%v", utils.ErrInfo(err))
					continue
				}
				if len(privateKey) > 0 {
					rsaPrivateKey, err := utils.MakePrivateKey(privateKey)
					if err != nil {
						log.Error("%v", utils.ErrInfo(err))
						continue
					}
					decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, rsaPrivateKey, utils.HexToBin([]byte(data["message"])))
					if err != nil {
						log.Error("%v", utils.ErrInfo(err))
						continue
					}
					if len(decrypted) > 0 {
						err = c.ExecSql(`UPDATE chat SET enc_message = message, message = ?, status = ? WHERE id = ?`, decrypted, 2, data["id"])
						if err != nil {
							log.Error("%v", utils.ErrInfo(err))
							continue
						}
						message = string(decrypted)
						status = "2"
					}
				}
			}
		}

		name := data["sender"]
		ava := "/static/img/noavatar.png"
		// возможно у отпарвителя есть ник
		nameAvaBan, err := c.OneRow(`SELECT name, avatar, chat_ban FROM users WHERE user_id = ?`, sender).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// возможно юзер забанен
		if nameAvaBan["chat_ban"] == "1" {
			continue
		}
		if len(nameAvaBan["name"]) > 0 {
			name = nameAvaBan["name"]
		}

		minerStatus, err := c.Single(`SELECT status FROM miners_data WHERE user_id = ?`, sender).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if minerStatus == "miner" && len(nameAvaBan["avatar"]) > 0 {
			ava = nameAvaBan["avatar"]
		}

		row := ""
		message = template.HTMLEscapeString(message)
		avaHtml := `<img src="` + ava + `" onclick='setReceiver("` + name + `", "` + data["sender"] + `")'>`
		nameHtml := `<strong><a class="chatNick" onclick='setReceiver("` + name + `", "` + data["sender"] + `")'>` + name + `</a></strong>`
		if status == "2" { // успешно расшифровали
			row = `<tr><td>` + avaHtml + `` + nameHtml + `: <i class="fa fa-lock"></i> ` + message + `</td></tr>`
		} else if status == "1" && receiver == c.SessUserId { // либо нет ключа, либо какая-то ошибка
			row = `<tr><td>` + avaHtml + `` + nameHtml + `: <div id="comment_` + data["id"] + `" style="display: inline-block;"><input type="hidden" value="` + message + `" id="encrypt_comment_` + data["id"] + `"><a class="btn btn-default btn-lg" onclick="decrypt_comment(` + data["id"] + `, 'chat')"> <i class="fa fa-lock"></i> Decrypt</a></div></td></tr>`
		} else if status == "0" {
			row = `<tr><td>` + avaHtml + `` + nameHtml + `: ` + message + `</td></tr>`
		}
		result += row
		chatIds[c.SessUserId] = append(chatIds[c.SessUserId], utils.StrToInt(data["id"]))
		if first == "1" {
			if utils.StrToInt64(data["sign_time"]) < chatMinSignTime || chatMinSignTime == 0 {
				chatMinSignTime = utils.StrToInt64(data["sign_time"])
				log.Debug("chatMinSignTime", chatMinSignTime)
			}
		}
	}

	log.Debug("chat data: %v", result)
	chatStatus := "ok"
	if len(utils.ChatInConnections) == 0 || len(utils.ChatOutConnections) == 0 {
		chatStatus = "bad"
	}

	resultJson, _ := json.Marshal(map[string]string{"messages": result, "chatStatus": chatStatus})

	return string(resultJson), nil
}
예제 #2
0
func (c *Controller) SaveDecryptComment() (string, error) {

	if c.SessRestricted != 0 {
		return "", utils.ErrInfo(errors.New("Permission denied"))
	}

	c.r.ParseForm()
	commentType := c.r.FormValue("type")
	id := utils.StrToInt64(c.r.FormValue("id"))
	comment := c.r.FormValue("comment")
	if !utils.InSliceString(commentType, []string{"chat", "dc_transactions", "arbitrator", "seller", "cash_requests", "comments"}) {
		return "", utils.ErrInfo(errors.New("incorrect type"))
	}

	// == если мы майнер и это dc_transactions, то сюда прислан зашифрованный коммент, который можно расшифровать только нод-кдючем
	minerId, err := c.GetMinerId(c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if minerId > 0 && utils.InSliceString(commentType, []string{"dc_transactions", "arbitrator", "seller"}) {
		nodePrivateKey, err := c.GetNodePrivateKey(c.MyPrefix)
		// расшифруем коммент
		rsaPrivateKey, err := utils.MakePrivateKey(nodePrivateKey)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		comment_, err := rsa.DecryptPKCS1v15(rand.Reader, rsaPrivateKey, utils.HexToBin([]byte(comment)))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		comment = string(comment_)
	}
	comment = template.HTMLEscapeString(comment)
	if len(comment) > 0 {
		if utils.InSliceString(commentType, []string{"arbitrator", "seller"}) {
			err = c.ExecSql(`
				UPDATE `+c.MyPrefix+`my_comments
				SET comment = ?,
					comment_status = ?
				WHERE id = ? AND type = ?`, comment, "decrypted", id, commentType)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		} else if commentType == "chat" {
			err = c.ExecSql(`
				UPDATE chat
				SET enc_message = message,
					message = ?,
					status = ?
				WHERE id = ? AND receiver = ?`, comment, 2, id, c.SessUserId)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		} else {
			err = c.ExecSql(`
				UPDATE `+c.MyPrefix+`my_`+commentType+`
				SET comment = ?,
					comment_status = 'decrypted'
				WHERE id = ?`, comment, id)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}
	} else {
		comment = "NULL"
	}
	return comment, nil
}
예제 #3
0
파일: tests.go 프로젝트: dzyk/dcoin-go
func MakeFrontTest(transactionArray [][]byte, time int64, dataForSign string, txType string, userId int64, MY_PREFIX string, blockId int64) error {

	db := DbConn()

	priv, pub := genKeys()

	nodeArr := []string{"new_admin", "votes_node_new_miner", "NewPct"}
	var binSign []byte
	if utils.InSliceString(txType, nodeArr) {

		err := db.ExecSql("UPDATE my_node_keys SET private_key = ?", priv)
		if err != nil {
			return utils.ErrInfo(err)
		}
		err = db.ExecSql("UPDATE miners_data SET node_public_key = [hex] WHERE user_id = ?", pub, userId)
		if err != nil {
			return utils.ErrInfo(err)
		}

		k, err := db.GetNodePrivateKey(MY_PREFIX)
		if err != nil {
			return utils.ErrInfo(err)
		}
		fmt.Println("k", k)
		privateKey, err := utils.MakePrivateKey(k)
		if err != nil {
			return utils.ErrInfo(err)
		}
		//fmt.Println("privateKey.PublicKey", privateKey.PublicKey)
		//fmt.Println("privateKey.D", privateKey.D)
		//fmt.Printf("privateKey.N %x\n", privateKey.N)
		//fmt.Println("privateKey.Public", privateKey.Public())
		binSign, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, utils.HashSha1(dataForSign))
		//nodePublicKey, err := db.GetNodePublicKey(userId)
		//fmt.Println("nodePublicKey", nodePublicKey)
		//if err != nil {
		//	return utils.ErrInfo(err)
		//}
		//CheckSignResult, err := utils.CheckSign([][]byte{nodePublicKey}, dataForSign, binSign, true);
		//fmt.Printf("binSign: %x\n", binSign)
		//fmt.Println("err", err)
		//fmt.Println("CheckSignResult", CheckSignResult)

	} else {

		err := db.ExecSql("UPDATE my_keys SET private_key = ?", priv)
		if err != nil {
			return utils.ErrInfo(err)
		}
		err = db.ExecSql("UPDATE users SET public_key_0 = [hex]", pub)
		if err != nil {
			return utils.ErrInfo(err)
		}

		k, err := db.GetPrivateKey(MY_PREFIX)
		privateKey, err := utils.MakePrivateKey(k)
		if err != nil {
			return utils.ErrInfo(err)
		}
		binSign, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, utils.HashSha1(dataForSign))
		binSign = utils.EncodeLengthPlusData(binSign)
	}

	//fmt.Println("HashSha1", utils.HashSha1(dataForSign))
	//fmt.Printf("binSign %x\n", binSign)
	//fmt.Println("dataForSign", dataForSign)
	transactionArray = append(transactionArray, binSign)

	parser := new(dcparser.Parser)
	parser.DCDB = db
	parser.GoroutineName = "test"
	parser.TxSlice = transactionArray
	parser.BlockData = &utils.BlockData{BlockId: blockId, Time: time, UserId: userId}
	parser.TxHash = []byte("111111111111111")
	parser.Variables, _ = parser.DCDB.GetAllVariables()

	err0 := utils.CallMethod(parser, txType+"Init")
	if i, ok := err0.(error); ok {
		fmt.Println(err0.(error), i)
		return err0.(error)
	}
	err0 = utils.CallMethod(parser, txType+"Front")
	if i, ok := err0.(error); ok {
		fmt.Println(err0.(error), i)
		return err0.(error)
	}
	err0 = utils.CallMethod(parser, txType+"RollbackFront")
	if i, ok := err0.(error); ok {
		fmt.Println(err0.(error), i)
		return err0.(error)
	}
	return nil
}