implement choices_cost

This commit is contained in:
nemunaire 2018-12-02 23:18:32 +01:00
parent f9abdd23c6
commit 476f0f553c
18 changed files with 180 additions and 24 deletions

View File

@ -270,6 +270,7 @@ type uploadedFlag struct {
ValidatorRe *string `json:"validator_regexp"`
Flag string
Value []byte
ChoicesCost int64
}
func createExerciceFlag(exercice fic.Exercice, body []byte) (interface{}, error) {
@ -287,7 +288,7 @@ func createExerciceFlag(exercice fic.Exercice, body []byte) (interface{}, error)
vre = uk.ValidatorRe
}
return exercice.AddRawFlag(uk.Label, uk.Help, uk.IgnoreCase, vre, []byte(uk.Flag))
return exercice.AddRawFlag(uk.Label, uk.Help, uk.IgnoreCase, vre, []byte(uk.Flag), uk.ChoicesCost)
}
func showExerciceFlag(flag fic.Flag, _ fic.Exercice, body []byte) (interface{}, error) {
@ -309,6 +310,7 @@ func updateExerciceFlag(flag fic.Flag, exercice fic.Exercice, body []byte) (inte
flag.Help = uk.Help
flag.IgnoreCase = uk.IgnoreCase
flag.Checksum = uk.Value
flag.ChoicesCost = uk.ChoicesCost
if uk.ValidatorRe != nil && len(*uk.ValidatorRe) > 0 {
flag.ValidatorRegexp = uk.ValidatorRe

View File

@ -66,7 +66,7 @@ type ExerciceFlagUCQ struct {
ValidatorRe string `toml:"validator_regexp,omitempty"`
Help string `toml:",omitempty"`
DisplayAs string `toml:",omitempty"`
Choices_Cost int64 `toml:",omitempty"`
ChoicesCost int64 `toml:"choices_cost,omitempty"`
Choice []ExerciceFlagUCQChoice
LockedFile []ExerciceUnlockFile `toml:"unlock_file,omitempty"`
NeedFlag []ExerciceDependency `toml:"need_flag,omitempty"`

View File

@ -52,7 +52,7 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1))
}
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw)); err != nil {
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw), 0); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue
} else {
@ -94,7 +94,7 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag UCQ #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1))
}
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw)); err != nil {
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw), flag.ChoicesCost); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag UCQ #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue
} else {
@ -205,7 +205,7 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
errs = append(errs, fmt.Sprintf("%q: error in MCQ %d choice %d: %s", path.Base(exercice.Path), nline + 1, cid, err))
continue
} else if len(justify) > 0 {
if _, err := exercice.AddRawFlag(fmt.Sprintf("%%%d%%%s", e.Id, choice.Help), "", false, nil, []byte(justify)); err != nil {
if _, err := exercice.AddRawFlag(fmt.Sprintf("%%%d%%%s", e.Id, choice.Help), "", false, nil, []byte(justify), 0); err != nil {
errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue
}

38
backend/choices.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"encoding/json"
"log"
"io/ioutil"
"os"
"srs.epita.fr/fic-server/libfic"
)
type wantChoices struct {
FlagId int64 `json:"id"`
}
func treatWantChoices(pathname string, team fic.Team) {
var ask wantChoices
if cnt_raw, err := ioutil.ReadFile(pathname); err != nil {
log.Println("[ERR]", err)
} else if err := json.Unmarshal(cnt_raw, &ask); err != nil {
log.Println("[ERR]", err)
} else if ask.FlagId == 0 {
log.Println("[WRN] Invalid content in wantChoices file: ", pathname)
os.Remove(pathname)
} else if flag, err := fic.GetFlag(ask.FlagId); err != nil {
log.Println("[ERR]", err)
} else if err := team.DisplayChoices(flag); err != nil {
log.Println("[ERR]", err)
} else {
if err := genTeamMyFile(team); err != nil {
log.Println("my-", team.Id, ".json generation error: ", err)
}
if err := os.Remove(pathname); err != nil {
log.Println("[ERR]", err)
}
}
}

View File

@ -169,6 +169,8 @@ func treat(raw_path string) {
treatRename(raw_path, team)
case "hint":
treatOpeningHint(raw_path, team)
case "choices":
treatWantChoices(raw_path, team)
default:
treatSubmission(raw_path, team, spath[2])
}

View File

@ -188,6 +188,20 @@ server {
proxy_redirect off;
}
location /wantchoices/ {
#auth_basic "Secure Zone";
#auth_basic_user_file ficpasswd;
include /etc/nginx/auth.conf;
rewrite ^/wantchoices/(.*)$ /wantchoices/$team/$1 break;
proxy_pass http://localhost:8080/;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host localhost;
proxy_redirect off;
}
location = /events.json {
proxy_pass http://localhost:8081/api/events/;
proxy_method GET;

View File

@ -175,6 +175,15 @@ server {
rewrite ^/openhint/(.*)$ /openhint/$team/$1 break;
proxy_pass http://frontend:8080/;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_redirect off;
}
location /wantchoices/ {
include fic-auth.conf;
rewrite ^/wantchoices/(.*)$ /wantchoices/$team/$1 break;
proxy_pass http://frontend:8080/;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_redirect off;

19
frontend/choices.go Normal file
View File

@ -0,0 +1,19 @@
package main
import (
"net/http"
"path"
"time"
)
func WantChoicesHandler(w http.ResponseWriter, r *http.Request, team string, sURL []string) {
if time.Now().Sub(challengeEnd) > 0 {
http.Error(w, "{\"errmsg\":\"Le challenge est terminé, trop tard !\"}", http.StatusGone)
return
}
// Enqueue file for backend treatment
if saveTeamFile(path.Join(team, "choices"), w, r) {
http.Error(w, "{\"errmsg\":\"Demande de choix acceptée...\"}", http.StatusAccepted)
}
}

View File

@ -47,6 +47,7 @@ func main() {
// Register handlers
http.Handle(fmt.Sprintf("%s/chname/", *prefix), http.StripPrefix(fmt.Sprintf("%s/chname/", *prefix), submissionTeamChecker{"name change", ChNameHandler, *teamsDir}))
http.Handle(fmt.Sprintf("%s/openhint/", *prefix), http.StripPrefix(fmt.Sprintf("%s/openhint/", *prefix), submissionTeamChecker{"opening hint", HintHandler, *teamsDir}))
http.Handle(fmt.Sprintf("%s/wantchoices/", *prefix), http.StripPrefix(fmt.Sprintf("%s/wantchoices/", *prefix), submissionTeamChecker{"wantint choices", WantChoicesHandler, *teamsDir}))
http.Handle(fmt.Sprintf("%s/registration/", *prefix), http.StripPrefix(fmt.Sprintf("%s/registration/", *prefix), submissionChecker{"registration", RegistrationHandler}))
http.Handle(fmt.Sprintf("%s/resolution/", *prefix), http.StripPrefix(fmt.Sprintf("%s/resolution/", *prefix), ResolutionHandler{}))
http.Handle(fmt.Sprintf("%s/submission/", *prefix), http.StripPrefix(fmt.Sprintf("%s/submission/", *prefix), submissionTeamChecker{"submission", SubmissionHandler, *teamsDir}))

View File

@ -426,6 +426,30 @@ angular.module("FICApp", ["ngRoute", "ngSanitize"])
});
$scope.my.exercices[$rootScope.current_exercice].submitted = true;
};
$scope.wantchoices = function(kid) {
$scope.my.exercices[$rootScope.current_exercice].flags[kid].wcsubmitted = true;
$http({ url: "/wantchoices/" + $rootScope.current_exercice, method: "POST", data: { id: Math.floor(kid) } }).then(function(response) {
var checkDiffWC = function() {
$http.get("/my.json").then(function(response) {
var my = response.data;
if (my.exercices[$rootScope.current_exercice].flags[kid].choices)
$rootScope.recvMy(my);
else {
if (cbd)
$timeout.cancel(cbd);
cbd = $timeout(checkDiffWC, 750);
}
});
};
checkDiffWC();
}, function(response) {
$scope.messageClass = {"text-danger": true};
$scope.sberr = "Oups !";
$scope.message = response.data.errmsg;
$scope.my.exercices[$rootScope.current_exercice].flags[kid].wcsubmitted = false;
});
}
})
.controller("MyTeamController", function($scope, $http, $rootScope, $timeout) {
$rootScope.current_theme = 0;

View File

@ -88,8 +88,16 @@
<div class="form-group" ng-repeat="(kid,key) in my.exercices[current_exercice].flags">
<label for="sol_{{ kid }}">{{ key.label }}&nbsp;:</label>
<span ng-if="key.found && key.value" ng-bind="key.value"></span>
<input type="text" class="form-control" id="sol_{{ kid }}" autocomplete="off" name="sol_{{ kid }}" ng-model="key.value" ng-if="!key.found && !key.choices">
<select class="custom-select" id="sol_{{ kid }}" name="sol_{{ kid }}" ng-model="key.value" ng-if="!key.found && key.choices" ng-options="l as v for (l, v) in key.choices"></select>
<div class="input-group">
<input type="text" class="form-control" id="sol_{{ kid }}" autocomplete="off" name="sol_{{ kid }}" ng-model="key.value" ng-if="!key.found && !key.choices">
<select class="custom-select" id="sol_{{ kid }}" name="sol_{{ kid }}" ng-model="key.value" ng-if="!key.found && key.choices" ng-options="l as v for (l, v) in key.choices"></select>
<div class="input-group-append" ng-if="key.choices_cost">
<button class="btn btn-success" type="button" ng-click="wantchoices(kid)" ng-class="{disabled: key.wcsubmitted}" title="Cliquez pour échanger ce champ de texte par une liste de choix. L'opération vous coûtera {{ key.choices_cost }} points.">
<span class="glyphicon glyphicon-tasks" aria-hidden="true"></span>
Liste de propositions ({{ key.choices_cost }} points)
</button>
</div>
</div>
<small class="form-text text-muted" ng-if="!key.found && key.help.length > 0" ng-bind="key.help"></small>
<span class="glyphicon glyphicon-ok form-control-feedback text-success" aria-hidden="true" ng-if="key.found" title="Flag trouvé à {{ key.found | date:'mediumTime'}}"></span>
</div>

View File

@ -23,9 +23,9 @@
<div class="col-sm-10">
<div class="input-group">
<input type="text" class="form-control" id="newName" ng-model="newName" placeholder="{{ my.name }}">
<span class="input-group-btn">
<div class="input-group-append">
<button type="submit" class="btn btn-info">Valider</button>
</span>
</div>
</div>
</div>
</div>

View File

@ -170,6 +170,7 @@ CREATE TABLE IF NOT EXISTS exercice_flags(
ignorecase BOOLEAN NOT NULL DEFAULT 0,
validator_regexp VARCHAR(255) NULL,
cksum BINARY(64) NOT NULL,
choices_cost INTEGER NOT NULL,
FOREIGN KEY(id_exercice) REFERENCES exercices(id_exercice)
) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
`); err != nil {
@ -295,6 +296,18 @@ CREATE TABLE IF NOT EXISTS team_hints(
FOREIGN KEY(id_hint) REFERENCES exercice_hints(id_hint),
FOREIGN KEY(id_team) REFERENCES teams(id_team)
) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
`); err != nil {
return err
}
if _, err := db.Exec(`
CREATE TABLE IF NOT EXISTS team_wchoices(
id_team INTEGER,
id_flag INTEGER,
time TIMESTAMP NOT NULL,
CONSTRAINT uc_displayed UNIQUE (id_team,id_flag),
FOREIGN KEY(id_flag) REFERENCES exercice_flags(id_flag),
FOREIGN KEY(id_team) REFERENCES teams(id_team)
) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
`); err != nil {
return err
}

View File

@ -290,7 +290,7 @@ func (f EFile) GetDepends() ([]Flag, error) {
if err := rows.Scan(&d); err != nil {
return nil, err
}
deps = append(deps, Flag{d, f.IdExercice, "", "", false, nil, []byte{}})
deps = append(deps, Flag{d, f.IdExercice, "", "", false, nil, []byte{}, 0})
}
if err := rows.Err(); err != nil {
return nil, err

View File

@ -24,11 +24,13 @@ type Flag struct {
ValidatorRegexp *string `json:"validator_regexp"`
// Checksum is the expected hashed flag
Checksum []byte `json:"value"`
// ChoicesCost is the number of points lost to display choices.
ChoicesCost int64 `json:"choices_cost"`
}
// GetFlags returns a list of flags comming with the challenge.
func (e Exercice) GetFlags() ([]Flag, error) {
if rows, err := DBQuery("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil {
if rows, err := DBQuery("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil {
return nil, err
} else {
defer rows.Close()
@ -38,7 +40,7 @@ func (e Exercice) GetFlags() ([]Flag, error) {
var k Flag
k.IdExercice = e.Id
if err := rows.Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum); err != nil {
if err := rows.Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum, &k.ChoicesCost); err != nil {
return nil, err
}
@ -52,9 +54,15 @@ func (e Exercice) GetFlags() ([]Flag, error) {
}
}
// GetFlag returns a list of flags comming with the challenge.
func GetFlag(id int64) (k Flag, err error) {
err = DBQueryRow("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost FROM exercice_flags WHERE id_flag = ?", id).Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum, &k.ChoicesCost)
return
}
// GetFlagByLabel returns a flag matching the given label.
func (e Exercice) GetFlagByLabel(label string) (k Flag, err error) {
err = DBQueryRow("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum FROM exercice_flags WHERE type LIKE ? AND id_exercice = ?", label, e.Id).Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum)
err = DBQueryRow("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost FROM exercice_flags WHERE type LIKE ? AND id_exercice = ?", label, e.Id).Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum, &k.ChoicesCost)
return
}
@ -65,7 +73,7 @@ func getHashedFlag(raw_value []byte) [blake2b.Size]byte {
}
// AddRawFlag creates and fills a new struct Flag, from a non-hashed flag, and registers it into the database.
func (e Exercice) AddRawFlag(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte) (Flag, error) {
func (e Exercice) AddRawFlag(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte, choicescost int64) (Flag, error) {
if ignorecase {
raw_value = bytes.ToLower(raw_value)
}
@ -82,11 +90,11 @@ func (e Exercice) AddRawFlag(name string, help string, ignorecase bool, validato
}
hash := getHashedFlag(raw_value)
return e.AddFlag(name, help, ignorecase, validator_regexp, hash[:])
return e.AddFlag(name, help, ignorecase, validator_regexp, hash[:], choicescost)
}
// AddFlag creates and fills a new struct Flag, from a hashed flag, and registers it into the database.
func (e Exercice) AddFlag(name string, help string, ignorecase bool, validator_regexp *string, checksum []byte) (Flag, error) {
func (e Exercice) AddFlag(name string, help string, ignorecase bool, validator_regexp *string, checksum []byte, choicescost int64) (Flag, error) {
// Check the regexp compile
if validator_regexp != nil {
if _, err := regexp.Compile(*validator_regexp); err != nil {
@ -94,12 +102,12 @@ func (e Exercice) AddFlag(name string, help string, ignorecase bool, validator_r
}
}
if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, validator_regexp, cksum) VALUES (?, ?, ?, ?, ?, ?)", e.Id, name, help, ignorecase, validator_regexp, checksum); err != nil {
if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost) VALUES (?, ?, ?, ?, ?, ?, ?)", e.Id, name, help, ignorecase, validator_regexp, checksum, choicescost); err != nil {
return Flag{}, err
} else if kid, err := res.LastInsertId(); err != nil {
return Flag{}, err
} else {
return Flag{kid, e.Id, name, help, ignorecase, validator_regexp, checksum}, nil
return Flag{kid, e.Id, name, help, ignorecase, validator_regexp, checksum, choicescost}, nil
}
}
@ -111,7 +119,7 @@ func (k Flag) Update() (int64, error) {
}
}
if res, err := DBExec("UPDATE exercice_flags SET id_exercice = ?, type = ?, help = ?, ignorecase = ?, validator_regexp = ?, cksum = ? WHERE id_flag = ?", k.IdExercice, k.Label, k.Help, k.IgnoreCase, k.ValidatorRegexp, k.Checksum, k.Id); err != nil {
if res, err := DBExec("UPDATE exercice_flags SET id_exercice = ?, type = ?, help = ?, ignorecase = ?, validator_regexp = ?, cksum = ?, choices_cost = ? WHERE id_flag = ?", k.IdExercice, k.Label, k.Help, k.IgnoreCase, k.ValidatorRegexp, k.Checksum, k.ChoicesCost, k.Id); err != nil {
return 0, err
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
@ -143,6 +151,8 @@ func (e Exercice) WipeFlags() (int64, error) {
return 0, err
} else if _, err := DBExec("DELETE FROM exercice_flags_deps WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
return 0, err
} else if _, err := DBExec("DELETE FROM team_wchoices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
return 0, err
} else if _, err := DBExec("DELETE FROM flag_choices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
return 0, err
} else if res, err := DBExec("DELETE FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil {
@ -173,7 +183,7 @@ func (k Flag) GetDepends() ([]Flag, error) {
if err := rows.Scan(&d); err != nil {
return nil, err
}
deps = append(deps, Flag{d, k.IdExercice, "", "", false, nil, []byte{}})
deps = append(deps, Flag{d, k.IdExercice, "", "", false, nil, []byte{}, 0})
}
if err := rows.Err(); err != nil {
return nil, err

View File

@ -29,15 +29,15 @@ func truncateTable(tables ...string) (error) {
// ResetGame resets all tables containing team attempts and solves.
func ResetGame() (error) {
return truncateTable("team_hints", "flag_found", "mcq_found", "exercice_solved", "exercice_tries")
return truncateTable("team_wchoices", "team_hints", "flag_found", "mcq_found", "exercice_solved", "exercice_tries")
}
// ResetExercices wipes out all challenges (both attempts and statements).
func ResetExercices() (error) {
return truncateTable("team_hints", "exercice_files_deps", "exercice_files", "flag_found", "exercice_flags_deps", "flag_choices", "exercice_flags", "exercice_solved", "exercice_tries", "exercice_hints", "mcq_found", "mcq_entries", "exercice_mcq", "exercice_tags", "exercices", "themes")
return truncateTable("team_wchoices", "team_hints", "exercice_files_deps", "exercice_files", "flag_found", "exercice_flags_deps", "flag_choices", "exercice_flags", "exercice_solved", "exercice_tries", "exercice_hints", "mcq_found", "mcq_entries", "exercice_mcq", "exercice_tags", "exercices", "themes")
}
// ResetTeams wipes out all teams, incluings members and attempts.
func ResetTeams() (error) {
return truncateTable("team_hints", "flag_found", "mcq_found", "exercice_solved", "exercice_tries", "team_members", "teams")
return truncateTable("team_wchoices", "team_hints", "flag_found", "mcq_found", "exercice_solved", "exercice_tries", "team_members", "teams")
}

View File

@ -173,6 +173,19 @@ func (t Team) OpenHint(h EHint) (error) {
return err
}
// SeeChoices checks if the Team has revealed the given choices.
func (t Team) SeeChoices(k Flag) (bool) {
var tm *time.Time
DBQueryRow("SELECT MIN(time) FROM team_wchoices WHERE id_team = ? AND id_flag = ?", t.Id, k.Id).Scan(&tm)
return tm != nil
}
// DisplayChoices registers to the database that the Team has now revealed.
func (t Team) DisplayChoices(k Flag) (error) {
_, err := DBExec("INSERT INTO team_wchoices (id_team, id_flag, time) VALUES (?, ?, ?)", t.Id, k.Id, time.Now())
return err
}
// CountTries gets the amount of attempts made by the Team and retrieves the time of the latest attempt.
func (t Team) CountTries(e Exercice) (int64, time.Time) {
var nb *int64

View File

@ -42,6 +42,7 @@ type myTeamFlag struct {
Solved *time.Time `json:"found,omitempty"`
Soluce string `json:"soluce,omitempty"`
Choices map[string]string `json:"choices,omitempty"`
ChoicesCost int64 `json:"choices_cost,omitempty"`
}
type myTeamExercice struct {
ThemeId int64 `json:"theme_id"`
@ -199,11 +200,13 @@ func MyJSONTeam(t *Team, started bool) (interface{}, error) {
flag.Help = k.Help
if choices, err := k.GetChoices(); err != nil {
return nil, err
} else {
} else if t == nil || k.ChoicesCost == 0 || t.SeeChoices(k) {
flag.Choices = map[string]string{}
for _, c := range choices {
flag.Choices[c.Value] = c.Label
}
} else {
flag.ChoicesCost = k.ChoicesCost
}
}