# These maps set all kinds of variables we can use later in our configuration. This fil
# should be stored under /etc/nginx/conf.d so that it is loaded whenever nginx starts.

# List of allowed origins, can only send one.
map $http_origin $allow_origin { 
        ~^https?://element.example.com$ $http_origin;
        ~^https?://call.example.com$ $http_origin;
        ~^https?://someserver.example.com$ $http_origin;
        # NGINX won't set empty string headers, so if no match, header is unset.
        default "";
}

# Client username from MXID
map $http_authorization $mxid_localpart {
  default                           $http_authorization;
  "~Bearer syt_(?<username>.*?)_.*" $username;
  ""                                $accesstoken_from_urlparam;
}

# Whether to upgrade HTTP connection
map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

#Extract room name from URI
map $request_uri $room_name {
  default "not_room";
  "~^/_matrix/(client|federation)/.*?(?:%21|!)(?<room>[\s\S]+)(?::|%3A)(?<domain>[A-Za-z0-9.\-]+)" "!$room:$domain";
}

# Choose sync worker based on the existence of "since" query parameter
map $arg_since $sync {
    default normal_sync;
    '' initial_sync;
}

# Extract username from access token passed as URL parameter
map $arg_access_token $accesstoken_from_urlparam {
    # Defaults to just passing back the whole accesstoken
    default   $arg_access_token;
    # Try to extract username part from accesstoken URL parameter
    "~syt_(?<username>.*?)_.*"           $username;
}

# Extract username from access token passed as authorization header
map $http_authorization $mxid_localpart {
    # Defaults to just passing back the whole accesstoken
    default                              $http_authorization;
    # Try to extract username part from accesstoken header
    "~Bearer syt_(?<username>.*?)_.*"    $username;
    # if no authorization-header exist, try mapper for URL parameter "access_token"
    ""                                   $accesstoken_from_urlparam;
}

